Merge completed development for ranch assistant 1.1.0

This commit is contained in:
AttilaNet
2026-11-08 12:26:56 +08:00
51 changed files with 4621 additions and 1589 deletions
+58 -5
View File
@@ -1,11 +1,64 @@
# 牧羊人之心Bot
原生 PySide6 桌面辅助,当前版本 **1.1.0**,适配《牧羊人之心》Android **1.9.68**。
支持多账号独立运行、牧场培养、每日事务、自动扫荡及本地掉落分析。
## 运行指引
1. 在 Windows 中安装 Python 3,并确保 `python` 命令可用。
2. 按照[辅助使用说明](ranch_assistant/README.md)安装 PySide6 等依赖。
2. 在项目目录执行 `python -m pip install -r ranch_assistant/requirements.txt`,安装 PySide6 等依赖。
3. 双击项目根目录下的 `Start_Ranch_Helper.cmd` 启动辅助。
4. 在“登录”页面输入账号和密码,登录后选择区服;详细功能及配置方法见[辅助使用说明](ranch_assistant/README.md)。
5. 登录后自动刷新状态;配置各页面的功能后,用顶部“开启策略 / 关闭策略”统一控制自动操作。关闭策略后仍继续刷新。
也可以在项目目录运行 `python -m ranch_assistant` 启动。
首次使用可先查看各页面数据、配置规则,再开启策略;重启、恢复会话或导入配置后,策略开关默认关闭。
## 当前功能
| 模块 | 1.1.0 已具备的功能 |
| --- | --- |
| 登录与多账号 | 第一弹渠道账号密码登录,选择官方返回的区服及角色;账号密码与会话在本机加密保存,支持恢复会话、多账号独立运行、退出登录及清除登录记录。关闭账号页签后重启不会重新打开,也可彻底移除该账号的本地记录。 |
| 状态刷新与策略开关 | 登录后自动刷新角色、培育室、背包及牧场状态;每个账号只有一个“开启策略 / 关闭策略”开关,菜单支持批量控制。关闭策略后仍同步状态和到期成长;手动刷新不触发消耗类自动操作。 |
| 玩家信息 | 显示等级、经验与下一级门槛、金币、氪金、体力;经验达到门槛及体力恢复到期时,在后台请求服务器结算并更新显示。 |
| 培育室 | 显示已开启、未开启、VIP坑位及魔物阶段、剩余时间和成熟资质;孵化与成长到期自动同步。普通坑位可在确认费用后扩建。 |
| 分类背包 | 魔物蛋、可使用物品、消耗品、材料、其他、装备分别展示;支持搜索和排序。每种蛋可配置孵化开关、优先级、孵出后去向、补货下限/目标及市场;物品可配置赠礼开关和保留数量。 |
| 牧场与魔物管理 | 默认平铺全部魔物,可切换为按牧场折叠分组;显示容量、空位、等级与突破上限、资质、参考属性、好感上限及喜欢的物品。支持详情查看、多选锁定/解锁、派遣、指定喂养,以及确认费用后新建牧场。 |
| 自动孵蛋与补货 | 按手动规则完成金币市场买蛋/抽蛋、孵化、成长同步、成熟收取、派遣或喂养;支持优先十连、金币保留和每日购蛋额度。空坑按优先级独立随机1~2秒装填,不受整体刷新间隔影响。 |
| 资质保留与经验喂养 | 支持星级、综合资质、四项全S(4S)保护,另可保留资质严格高于牧场同种培养代表的新魔物。经验喂养按目标优先级批量提交素材,遵守当前突破上限与停止等级,保护锁定、在队和委托所需魔物。 |
| 自动赠礼与好感培养 | 在背包选择物品、牧场选择目标后自动赠礼;支持喜欢物品筛选、赠礼间隔、库存保留及当前好感上限。可自动为每种魔物选择唯一培养代表,依次按等级、好感、成长资质比较,完全相同时随机选定并记住。 |
| 每日事务 | 查看并领取每日签到礼包、七日签到、累计奖励、已有VIP日奖和邮件附件;支持手动领取及按勾选项目自动领取。 |
| 自动委托 | 根据每日剩余次数、城市与库存接取委托,推进已满足条件的步骤并领奖;显示金币和氪金奖励,金币、道具及魔物提交可分别限制。需要实战的步骤等待用户在游戏内完成。 |
| 自动扫荡 | 按地区折叠显示关卡、难度、通关星级及可能掉落;账号地图首次读取后本地缓存,仅手动刷新关卡时重新获取。逐关勾选、选择已解锁难度和本日次数上限,配置保留体力与战队;处理普通扫荡及探索奖励事件,记录实际奖励。 |
| 掉落数据分析 | 按账号、关卡与难度在本地保存扫荡记录,分别统计普通扫荡、奖励事件或合计;展示样本数、出现次数、总数量、实测掉落率、平均数量和95%区间。支持掉落率/每点体力获得数量的条形图,不额外请求游戏服务器。 |
| 收益资料与执行计划 | 内置749种魔物的培育时间、派遣金币、强化经验及每小时收益,支持名称/星级筛选和CSV/XLSX覆盖;执行计划显示下一步操作与等待原因。 |
| 统一策略配置 | 规则修改后自动保存并应用;通过原生菜单保存、导入或导出当前账号的孵蛋、牧场、喂养、赠礼、委托、每日事务、扫荡、刷新间隔及自定义收益资料。跨账号按魔物种类匹配培养目标,导出文件不包含账号凭据。 |
| 界面与调试 | 原生Qt菜单、可调整和隐藏的日志区、各页右键刷新;数字与勾选项可排序,数字框获得焦点后才响应滚轮,下拉框按内容扩宽。独立调试窗口查看请求、响应、耗时与错误,支持复制、导出和本地脱敏日志。 |
| 后台处理与离线演示 | 各账号后台线程独立处理网络与资料,单账号请求串行;只渲染当前查看页面,大列表分批更新并复用控件。支持随机30秒、60秒、2分钟或5分钟上限的刷新间隔,以及无需连接服务器的离线演示。 |
## 1.1.0 更新重点
- 重整登录、培育室、分类背包和牧场页面,合并魔物与牧场展示,保留平铺/分组切换。
- 打通按蛋规则补货、孵化、成长同步、收取、派遣及批量喂养的流程,增加4S和同种资质提升保护。
- 增加自动赠礼与同种唯一培养代表,避免重复培养多只同种魔物。
- 统一策略自动保存及跨账号导入/导出,将监控与执行控制简化为一个策略开关。
- 完善等级、体力、账号关闭/移除和本地地图缓存;扫荡奖励与事件分别处理,新增掉落概率及体力效率分析。
- 优化双账号、大量魔物及背包库存下的刷新响应,修复表格控件、下拉框裁字、滚轮误改数值和成长资质显示等问题。
## 功能范围与数据
当前登录适配第一弹渠道;需要短信验证的登录流程尚未提供验证码界面。
自动扫荡仅用于已满足游戏原有条件的普通关卡,首次通关、特殊关卡及委托战斗仍需在游戏内手动完成;不再提供手机截图配置或ADB自动战斗。
地图与可能掉落来自客户端静态配置,实际奖励以服务器响应为准;统计概率为本账号已确认样本的实测值。
“每点体力数量”按已知消耗样本的物品总量除以实际扣除体力计算,未知消耗不参与。
资料包含1178个关卡和2079种道具名称;客户端或接口更新后可能需要重新适配。
账号凭据、策略、地图缓存、购蛋/扫荡记录及统计数据库均保存在本机 `local_state/ranch_helper/`,按账号和角色隔离。
本次发布通过 **201项本地测试**,覆盖会话隔离、策略开关、培养流程、奖励处理、统计与界面响应;测试使用模拟数据和模拟服务,不代表所有功能均已通过真实账号验证。
详细配置与实现范围见[辅助使用说明](ranch_assistant/README.md)。
## 项目目录与测试
- `ranch_assistant/`:原生 PySide6 界面、登录会话、手动孵蛋规则、牧场管理及测试。
- `analysis/`:接口清单、行为分析、原始反编译源码及部分审计证据。
@@ -15,18 +68,18 @@
运行测试:
```console
python -m unittest discover -s ranch_assistant/tests -v
python -B -m unittest discover -s ranch_assistant/tests -v
```
这是本地 Git 仓库。原始 APK、构建包、第三方工具、签名材料、账号会话、
原始 APK、构建包、第三方工具、签名材料、账号会话、
密码、数据库、截图和运行日志均由 `.gitignore` 排除;账户数据仍保存在本机。
## 适配版本
| 辅助版本 | 《牧羊人之心》Android 客户端版本 | 状态 |
| --- | --- | --- |
| 1.1.0(`v1.1.0`) | 1.9.68 | 当前适配版本 |
| 1.0.0(`v1.0.0`) | 1.9.68 | 历史版本 |
| 1.1.0(`v1.1.0`) | 1.9.68 | 当前正式版本,已合并至 `main` |
| 1.0.0(`v1.0.0`) | 1.9.68 | 已发布版本 |
本表仅记录已经分析、测试的版本对应关系,不代表对其他客户端版本的兼容承诺。
+92 -102
View File
@@ -1,34 +1,56 @@
# 牧羊人之心牧场辅助
原生 PySide6 窗口,使用 Qt 默认控件。双击项目根目录的
`Start_Ranch_Helper.cmd` 启动。这台机器所需依赖已经存在。
其他环境可先运行 `python -m pip install -r ranch_assistant/requirements.txt`。
`Start_Ranch_Helper.cmd` 启动。当前辅助版本为 **1.1.0**,适配游戏 **1.9.68**。
首次运行请先执行 `python -m pip install -r ranch_assistant/requirements.txt`。
完整功能与版本摘要见[项目README](../README.md)。
底部日志区可拖动与页面之间的分隔条来调大或调小;顶部“隐藏日志 / 显示日志”切换显隐。
隐藏期间仍继续记录日志,重新显示恢复上次高度;高度和显隐状态随账号/角色配置保存。
孵蛋优先级、补货下限/目标和魔物喂养优先级均可直接输入数字,没有上下箭头。
横向、纵向滚动条均加宽为22个逻辑像素;仅调整滚动条,窗口与按钮保持原样。
下拉框默认加宽,表格中的操作、市场和难度列同步留足宽度;弹出列表按最长选项展开,并为滚动条预留宽度。
超过屏幕宽度的文字可横向滚动。
下拉框收起时悬停可查看完整选项,动态加载的区服、市场和魔物名称会重新计算宽度。
规则修改后自动保存并应用,无需点击保存按钮;连续输入会合并保存,尚未完整的输入不会覆盖已保存配置。
数字输入框仅在点击或键盘切换获得焦点后响应滚轮;未聚焦时滚动页面,不修改数字。
主窗口使用原生菜单栏:“账号”管理页签和保存会话,“策略”提供全部账号策略的开启/关闭,“策略配置”操作当前选中账号,“帮助 → 关于”显示版本号。
“保存当前账号策略”(Ctrl+S)可立即保存并应用当前配置,自动保存仍然有效。
勾选状态、优先级、孵出后的处理方式及保留数量都支持点击表头排序;刷新后保留排序,排序不改变策略优先级。
表格中的编号和名称靠左,星级、数量、优先级等内容及勾选框居中显示。
## 当前功能
- 登录与顶部信息:显示角色名、等级、累计经验/下一级经验、金币、氪金和体力。
“退出登录”保留登录记录;“退出登录并清除登录记录”经确认后只清除当前账号页签的凭据和会话。
- 培育室:已开启、未开启和VIP坑位分别显示;支持金币/氪金开普通坑位,先显示费用再确认。
- 背包:分为“魔物蛋”和“物品与装备”。魔物蛋逐种勾选孵化、设置优先级、选择孵出后派遣/喂养/保留,设置补货下限、目标和市场。
- 背包:按“魔物蛋、可使用、消耗品、材料、其他、装备”分别显示子标签。魔物蛋逐种勾选孵化、设置优先级、选择孵出后派遣/喂养/保留,设置补货下限、目标和市场。
数量归零后保留规则;可添加当前无库存的蛋。未勾选的蛋不会自动孵化或触发补货。
物品与装备支持分类和名称筛选,显示数量、品质和售价;可为物品设置赠礼开关及至少保留数量。
- 牧场:合并魔物与牧场列表,可按牧场筛选或查看全部魔物;按钮或右键可新建金币/氪金牧场,提交前确认费用。
各物品分类支持名称筛选,显示数量、品质和售价;可为物品设置赠礼开关及至少保留数量。只刷新当前打开的分类表格。
- 牧场:默认显示全部魔物,可手动切换为按牧场分组;按钮或右键可新建金币/氪金牧场,提交前确认费用。
“按牧场分组”使用可折叠树形:牧场标题显示数量、容量和空位,下方直接列出所属魔物;空牧场也保留显示,培育室魔物单独分组。
勾选喂养/赠礼目标并分别设置优先级;显示突破、当前等级上限、成长资质、参考属性、当前好感上限和喜欢的物品。
双击查看详情;右键可锁定、解锁、派遣、喂给指定魔物。
- 每个页面的表格和空白处可右键“刷新本页”;刷新只读取状态,不执行派遣、喂养等策略。
- 多账号:同一程序内多个独立账号页签,各自监控、自动执行、记录日志;切换页签不停止其他账号。
- 每个页面的表格和空白处可右键“刷新本页”;刷新会同步到期的成长状态,不执行派遣、喂养等消耗类策略。
- 多账号:同一程序内多个独立账号页签,登录后各自自动刷新状态,策略分别开启或关闭;切换页签不停止其他账号。
- 会话保存:成功读取角色后自动加密保存 Token、账号/区服/角色和请求编号,重启后可恢复。
- 自动孵蛋:按手动规则执行,提供开始执行、仅监控、停止按钮;支持十连优先、金币保留和每日购蛋额度。
5/10/30/60 秒刷新;喂养遵守当前突破上限,满级后转到下一喂养目标。
原“牧场策略”并入此页的“牧场与赠礼策略”子页;可导出、导入培养策略,跨账号按魔物种类匹配目标。
导入后所有自动执行开关保持关闭,文件不包含账号、密码、Token、会话或本机路径。
- 自动赠礼:在背包勾选可用物品,在牧场勾选目标并设置优先级,再到“牧场与赠礼策略”启用。
- 自动孵蛋:按手动规则执行,使用顶部统一的“开启策略 / 关闭策略”开关;支持十连优先、金币保留和每日购蛋额度。
可选随机30秒、60秒、2分钟或5分钟,每轮刷新完成后从0到所选上限重新取间隔;喂养遵守当前突破上限,满级后转到下一喂养目标。
空坑装填单独计时:有可用蛋时随机等待1~2秒装填一个坑位,确认成功后继续下一坑,不受整体刷新间隔影响。
每次装填前重新读取坑位和库存;无可用蛋、坑位已满或关闭策略时暂停。此快速计时不会执行购蛋、派遣或其他操作。
子页分为“孵蛋策略”“牧场策略”“喂养策略”,内容超出高度时滚动显示,修改后自动保存并应用。
“牧场策略”新增独立开关“保留资质高于牧场同种培养代表的新魔物”,与S/A/B/C、4S及星级保护分别生效。
同种培养代表优先选等级最高者,再依次比较好感、综合成长资质;新魔物的四项成长按各自范围归一化后取平均,严格更高才算提升。
同分不算提升;牧场尚无同种时保留首只,代表资质未同步完整时暂留。已有锁定、队伍及保留种类保护继续生效。
- 统一策略配置:通过主窗口菜单“策略配置”,保存、导入或导出当前账号的全部孵蛋、牧场、喂养、赠礼、委托、每日事务、扫荡及监控间隔设置,包含自定义收益资料。
跨账号按魔物种类匹配喂养和赠礼目标;牧场实例编号不跨账号复制,默认使用有空位的牧场。兼容旧版培养策略文件。
导入保留功能勾选和规则,策略开关保持关闭,核对后手动开启;文件不包含账号、密码、Token、会话或本机路径。
- 自动赠礼:独立页签,在背包勾选可用物品,在牧场勾选目标并设置优先级,再到“自动赠礼”启用。
每次消耗一件物品,默认只使用目标喜欢的物品;遵守当前羁绊好感上限、赠礼间隔、物品保留数量及委托保留。
勾选“每种魔物只培养一只,自动选择培养代表”后,自动为牧场中的每种魔物选一只,按等级 → 好感 → 综合成长资质排序,无需逐只勾选。
综合资质相同再比较四项成长;各项均相同时随机选定并按账号/角色记住。列表显示代表的ID、等级、好感和资质,“刷新 / 预览培养对象”可更新预览。
同种代表满好感或冷却时不改喂同种其他魔物;可继续处理其他种类。自动模式下代表会受自动派遣/喂养保护,手动模式保留原有目标优先级。
两个新开关均默认关闭,修改后自动保存并纳入统一策略导入/导出;选定实例保存在角色目录的 `cultivation_choices.json`,不跨账号复制。
- 收益资料:749 种魔物数据来自用户提供的 APK 1.9.68,支持名称搜索和1–5星分别筛选,
可导入 CSV/XLSX 覆盖价格、经验和时间。
- 账号密码登录:第一弹渠道密码验证 → 官方区服列表 → 选择区服并读取角色。
@@ -39,43 +61,48 @@
支持复制/导出,自动保存本地脱敏日志。
- 自动委托:按每日剩余接取次数、解锁城市和库存,接取、推进已满足条件的步骤、
领取奖励;列表显示奖励金币和氪金数量。提交金币、道具、魔物分别受策略限制。战斗步骤等待游戏实际完成。
- 地图关卡:按地区折叠显示安装包内的关卡、难度、掉落及账号解锁/通关记录,
- 自动扫荡:按地区分组,默认折叠显示关卡、难度、掉落及账号解锁/通关记录。
首次读取后按账号/角色保存本地地图缓存,重启、切换页面或普通监控刷新均复用缓存,仅“刷新关卡”(或本页右键刷新)更新列表。
每关可勾选、选择已解锁难度和本日上限;满足游戏原有条件的普通关卡可接口扫荡,
其余可设为 ADB 自动战斗目标。
其余请在游戏内手动战斗。
- 扫荡奖励:普通扫荡读取 `battleEnd.reward`,奖励事件读取 `stageEvent.result`,日志列出本次实际获得的物品、魔物蛋、金币和经验。
- 数据分析:紧邻“自动扫荡”的独立页签。左侧按地区选择关卡和难度,右侧显示条形图与掉落明细;关卡和可能掉落来自本地静态配置。
可分别查看普通扫荡、奖励事件或合计,显示样本数、出现次数、获得总数量、实测掉落率、每次平均数量及95%区间。
“每点体力数量”按已知消耗样本的获得数量除以实际扣除体力计算,图表可切换到该指标;未知消耗样本不参与,体力奖励返还单独列出。
无样本显示“—”;同次获得多件物品只计一次出现,实测掉落率为出现次数除以已确认样本数。
数据按账号/角色保存在本地 `sweep_rewards.sqlite3`,重启保留;首次后台补录现有调试日志中能匹配角色、关卡和成功结算的记录,重复响应不重复计数。
“刷新本地统计”仅读取本机数据;统计与图表不额外请求服务器,不上传数据。实测概率随样本变化,不代表官方掉率。
- 每日事务:集中查看每日签到礼包、七日签到、累计奖励、VIP日奖和邮件附件;
可立即领取勾选项目,或开启监控时自动领取。刷新本身只读。
- 页面截图配置:每个页面一个截图按钮,自动保存原图与设备、分辨率、关卡、难度。
截图无需登录或 Token,不会点击或切换手机页面;由助手查看样本后生成按钮配置。
- 布丁史莱姆牧场:通过 ADB 操作手机里的实际战斗;根据当前体力、
入场券和自定每日轮数决定是否继续,支持自动开战、倒计时、自动战斗、
结算按钮识别、失败停止和超时停止。完成一次界面标定后可循环运行。
可立即领取勾选项目,或开启顶部策略开关后自动领取;手动刷新不领奖。
- 离线演示:不连接游戏服务器即可查看数据、策略和模拟操作。
- 等级与体力:经验达到下一等级门槛时自动请求官方升级结算;按客户端150秒恢复周期请求体力结算并显示服务器返回值。
到期检查独立于随机刷新间隔,在账号后台线程串行执行;未开启消耗类策略时也会同步,退出登录或连接出错后停止。
## 连接真实角色
默认未登录,使用本地示例数据。顶部账号页签用于切换账号,“新增账号页签”用于登录另一账号。
默认未登录,使用本地示例数据。顶部账号页签用于切换账号,菜单“账号 → 新增账号页签”用于登录另一账号。
1. 在“登录”页填写第一弹渠道账号和密码,点击“账号密码登录并获取区服”。
默认勾选“记住账号和密码”;编辑完、点击登录或关闭窗口时自动保存,也可点击“保存登录信息”。
默认勾选“记住账号和密码”;编辑完、点击登录或关闭窗口时自动保存。
密码保存在本机加密文件 `local_state/ranch_helper/credentials.json`,重启自动填回,不再自动清空。
2. 从“官方返回的区服 / 已有角色”选择区服,点击“进入选中区服”。
登录中心取自 APK,游戏服务器地址取自选中区服的 `gameServerAddress`。
3. 确认真实角色名称、培育室和背包数量。成功后 Token 自动保存到该账号工作区的 `sessions/`,无需复制。
3. 确认角色名称、培育室和背包数量。成功后 Token 自动保存到该账号工作区的 `sessions/`,并开始自动刷新状态,无需另开监控。
4. 在“背包魔物蛋”逐种配置:勾选“孵化”,设置优先级(1最高),选择“孵出后”派遣、喂养或保留。
“低于补货”是可用蛋少于多少开始购买,0表示关闭;“补至”是希望补充到的可用蛋数量。
每行可选包含该蛋的金币市场;蛋用完后这一行仍会保留。规则自动保存。
5. 到“自动孵蛋”启用需要的买蛋、孵蛋、派遣、收取或喂养开关。
点“刷新 / 预览”查看下一步,再点“开始执行勾选功能”。页面会显示“执行中”、
下一步操作或等待原因。“仅监控”和手动刷新不会执行策略;“停止执行”保留只读监控。
已经发送的请求会返回,停止后不发送下一项。重启或恢复会话后需重新点开始执行。
点“刷新 / 预览”查看下一步,再点击顶部“开启策略”。各页面只配置功能和规则,不再分别开始或停止。
点击“关闭策略”后仍会刷新状态、同步到期成长,但不再自动派遣、喂养、购蛋或领奖。手动刷新只更新状态。
已经发送的请求会正常返回,关闭后不发送下一项自动操作。重启或恢复会话后自动刷新,策略开关默认关闭。
6. 需要经验时,在“牧场”勾选接收经验的喂养目标并设置优先级。优先级数字小的先喂,达到当前突破上限后换下一个;
在“自动孵蛋 → 牧场与赠礼策略”可设全局停止等级、星级/资质保护和保留蛋数量。“收益资料”的星级勾选只筛选表格显示。
7. 需要提升好感时,在“背包 → 物品与装备”勾选物品并设置保留数量,在“牧场”勾选目标并设置赠礼优先级;
在“自动孵蛋 → 牧场与赠礼策略”启用自动赠礼。达到当前好感上限或仍在赠礼间隔时不会继续消耗物品。
同页可导出策略供其他账号导入;导入后需逐项核对并手动开启自动执行。
在“自动孵蛋 → 喂养策略”设置全局停止等级,在“牧场策略”设置星级/资质保护和保留蛋数量。“收益资料”的星级勾选只筛选表格显示。
7. 需要提升好感时,在“背包”的对应物品分类中勾选物品并设置保留数量,在“牧场”勾选目标并设置赠礼优先级;
在独立的“自动赠礼”页启用。达到当前好感上限或仍在赠礼间隔时不会继续消耗物品。
菜单“策略配置”可导出全部策略供其他账号导入;导入后需逐项核对并开启顶部策略开关。
可用“绿色史莱姆金币预设(仅孵此蛋)”快速设置:只勾选绿色史莱姆、优先级1、孵出后派遣、低于1补至10、
莉莉托斯市场。这个预设关闭喂养,保留4星以上/A资质魔物,仍需点击开始执行。
莉莉托斯市场。这个预设关闭喂养,保留4星以上/A资质魔物,仍需开启顶部策略开关。
“登录”页不再展示服务器地址、Token、密钥和请求编号,也不自动弹出调试窗;这些信息由程序内部处理。
莉莉托斯市场单次价格为100金币(本地客户端表),买到的蛋随机,不能指定全部为绿色史莱姆。
@@ -103,28 +130,32 @@
## 多账号与恢复会话
1. 每个账号使用独立页签。用顶部“新增账号页签”添加账号,用页签或“打开已保存账号”切换。
1. 每个账号使用独立页签。菜单“账号 → 新增账号页签”添加账号,用页签或“打开已保存账号”切换。
2. 每个账号首次在本版本正常登录一次;此前版本只保存在内存的 Token 不能从脱敏日志补回。
3. 重启后在“登录”页点击“恢复选中会话”,或在顶部点击“恢复各页签的保存会话”。
恢复会先读取角色并核对角色编号,成功后才显示为真实数据;不会自动开启策略或刷图。
4. 各页签可分别开启监控和自动执行。顶部“全部开始监控”只开启已连接账号的监控,
自动执行仍由各账号的勾选决定;“全部停止”停止所有页签的监控和刷图。
5. 关闭一个页签会停止该账号,其他账号继续运行;保存的账号和会话仍可再次打开。
3. 重启后在“登录”页点击“恢复选中会话”,或使用菜单“账号 → 恢复各页签的保存会话”。
恢复会先读取角色并核对角色编号,成功后才显示为真实数据;不会自动开启消耗类策略。
4. 登录或恢复会话成功后自动刷新状态,各账号只有一个顶部策略开关。
菜单“策略 → 开启全部账号策略 / 关闭全部账号策略”批量控制已连接账号;关闭策略后仍继续刷新。
5. 关闭页签会停止该账号,并立即保存关闭状态;重启后不再自动打开。账号记录仍可用“账号 → 打开已保存账号”重新打开。
退出整个程序时,会保留当时仍打开的页签;关闭所有页签后,下次启动保持空白。
6. 彻底删除本地账号记录:右键账号页签选“移除此账号…”,或用“账号 → 移除当前账号…”。
已关闭的账号可用“账号 → 移除已保存账号…”选择。确认后删除所选账号的本地密码、会话、策略、地图缓存和运行记录,不会注销游戏账号。
若有请求正在执行,先停止调度,待当前请求结束再移除;其他账号继续运行且记录保留。移除后重启也不会恢复该账号。
账号工作区各自保存凭据、会话和日志;区服/角色各自保存策略、喂养目标、截图和刷图次数。
账号工作区各自保存凭据、会话和日志;区服/角色各自保存策略、喂养目标和扫荡次数。
切换区服时不沿用其他角色的策略。相同账号区服不会在两个页签重复运行。
会话的请求编号在发送前保存,包括超时未确认的请求;写请求不会自动重发。
删除保存会话需先退出登录,再点击“删除选中保存会话”;也可使用“退出登录并清除登录记录”一次清理当前账号页签。
“记住账号和密码”只控制密码,独立于会话保存。
正常会话心跳按客户端的 240 秒周期运行。ADB 刷图中,同一台手机同时只允许一个账号页签控制;
不同手机可分别配置。未实现脚本检测规避,也不保证服务端无法识别自动化。
正常会话心跳按客户端的 240 秒周期运行;成长状态按阶段到期触发同步。需要实际战斗的关卡在游戏内手动进行。
## 页面数据与刷新
“培育室”“背包”“牧场”可直接查看状态,顶部显示坑位、蛋数量、物品、魔物、牧场数量和更新时间。
表格或页面空白处右键选择“刷新本页”,保持当前页面;请求进行中再次刷新会排队。
收益资料和截图配置页刷新本地资料。自动刷新的 5/10/30/60 秒间隔继续保留。
收益资料页刷新本地资料;已移至最后。状态轮询支持随机30秒、60秒、2分钟和5分钟,每轮完成后从0到所选上限取间隔。
当前客户端代码可确认240秒会话心跳和成长阶段到期结算,未找到统一的全量状态轮询周期;阶段同步独立于随机轮询,不必等下一轮。
已修复实际响应里 `activityHistory.vipInfo=null` 导致策略报错、阻止数据显示的问题。
已用实际角色响应回放验证 4 个坑位、4 类蛋、4 只魔物和 1 个牧场能显示。
@@ -179,18 +210,20 @@
## 手动管理与扩建
孵化与幼体成长阶段显示“待成熟后生成”,不把服务端的零值算成 C 资质。
自动执行会在两个阶段转换时请求成长结算,并使用结算响应中的阶段和四项成长值更新界面;
登录后在两个阶段到期时自动请求成长结算,并使用结算响应中的阶段和四项成长值更新界面;
成熟、资质确定后才决定派遣、喂养或保留,旧查询结果不会覆盖尚未确认回写的结算数据。
培育室的“同步孵化 / 成长”可单独更新这些状态,本次不执行派遣或喂养。
“仅监控”不会结算或派遣;需点“开始执行勾选功能”才能自动处理。
保留原因会显示在培育室建议和日志中,例如达到保留星级、综合资质A/S、锁定或未启用派遣。
培育室无需手动同步;登录后阶段到期会在后台同步,关闭策略后仍会检查。服务器暂未确认时会限频等待,避免连续发送。
派遣、喂养等自动操作由顶部策略开关统一控制。
资质保留条件新增“四项全S(4S)才保留”,要求攻、防、生命、敏捷分别为S;综合评级为S不等于4S。
锁定、队伍、保留星级、资料不完整等保护独立生效;若希望低星魔物仅按4S保留,请同时检查保留星级设置。
保留原因会显示在培育室建议和日志中。
培育室与牧场派遣都使用 `monsterService/monsterSell` 的 `monsterIds` 数组参数,
不需要先收取到牧场。旧版培育室误用了遗留包装的 `monsterId` 字段,会触发服务端997
“网络错误”;现已统一修正自动派遣和右键手动派遣。
培育室魔物的 `roomId=null` 已兼容,统计牧场容量时不会再因空字段中断整轮策略。
- 魔物表可多选,使用按钮或右键锁定/解锁。派遣、指定喂养会列出将消耗的魔物并要求确认;
这些手动操作会暂停自动执行。锁定、系统锁、羁绊、在队、探索、建筑中及已装备的魔物不能作为素材。
这些手动操作会关闭策略,状态刷新继续。锁定、系统锁、羁绊、在队、探索、建筑中及已装备的魔物不能作为素材。
- 喂养素材需已收取到牧场,目标不能是素材本身,且不能已满当前突破等级上限。
- 参考属性按基础值、成长、等级、潜能、好感及升星计算,不含装备、羁绊和全局加成;完整实战面板以游戏为准。
- 培育室按本地表列出11个坑位,并兼容服务器返回的更多位置。第4个为VIP专用,不走普通扩建接口。
@@ -201,69 +234,24 @@
费用变化会要求重新确认。取消确认不会发送请求,超时不会自动重复购买。
- 实测日志里的空坑是 `monsterId=-1`,已按客户端 `<=0` 规则修复;此前买到蛋却不孵化的原因就是误判空坑。
## 页面截图配置(推荐)
1. 手机启用 USB 调试并允许 ADB。在“体力刷图”填写 ADB 路径(本机已自动找到),
选择关卡和难度。只有一台手机时设备编号可留空。
2. 打开“页面截图配置”。自己玩到对应页面时,点击该行“截取此页面”。
每次截图会暂停当前辅助监控和刷图;不自动登录、开战或跳转页面。
3. 最少拍齐“关卡准备页”(标题、难度、进入按钮)和“胜利结算页”(胜利标识、确认按钮)。
按需补拍“战斗倒计时”“自动关闭”“自动开启”“后续确认”“失败结算”五页。
不必特意输一局来收集失败页。点击页面行可预览已有图片。
4. 截图自动保存在项目目录:
当前角色目录下的 `capture_profiles/<设备>/<宽x高>/<关卡>_<难度>/`。
登录角色的目录为 `<账号工作区>/roles/<角色标识>/`,软件会显示实际路径。
原图为页面英文标识命名的 PNG,`profile.json` 保存设备、分辨率、时间和图片摘要。
“打开截图文件夹”可查看;重启后通过下拉框找回配置。
5. 拍好后告知助手“截图好了”。助手直接读取此工作区的文件,查看按钮位置,
生成同目录 `buttons.json` 和裁剪模板,不需要你手工框选或提供 Token。
这一步由助手完成,Qt 程序本身不包含自动理解任意截图的模型。
6. 点击“加载已生成的按钮配置”,然后用真实会话核对体力、入场券,
让手机停在相同账号的所选关卡准备页,设置每日轮数,开始刷图。
按钮配置绑定设备、分辨率、关卡、难度及生成时的截图摘要。重新拍摄改变了内容,
或更换设备/分辨率时需要重新生成。胜利标识的识别位置和确认按钮的点击位置可分开。
保留“体力刷图”里的手工框选作为可选工具;推荐流程不需要使用它。
必须同时匹配关卡名称与进入按钮才会开始一轮。请保持同一画面布局,
不要手动切换其他关卡或应用。分辨率/界面布局变化后需要重新标定。
模板匹配无法理解任意游戏弹窗;未知画面会等待,并在单轮超时后停止。
当前 APK 的 `bd00` 一般难度数据为 6 体力 + 道具 20047 一枚入场券,
`bd01` 使用另外一种入场券;程序按对应关卡配置检查,不把“免费”当成
“不限次数”。本地每日轮数按北京时间和角色/关卡分别持久化,统计已开始
的尝试,包括中断或失败;它不是服务器的每日次数查询接口。服务器的
入场券余量也会独立检查。暂未找到该活动独立的每日次数字段,不声称已
读取到该字段,遇到服务器限制或未知弹窗会停止/超时退出自动流程。
## 文件与验证
- 工作区:首账号使用 `local_state/ranch_helper/`,新增账号使用其 `profiles/<编号>/`。
`sessions/` 是加密会话;`roles/<角色标识>/` 是各角色的策略、截图和本日次数。
`sessions/` 是加密会话;`roles/<角色标识>/` 是各角色的策略和本日次数。
- `catalog.json` 是本地数据;游戏热更新后的新魔物/新售价需要更新资料。
未知魔物和不完整资质不会自动派遣或喂养。
- 自定义表:`typeId, sell_money, sell_exp, time_total`(秒),可只提供部分
覆盖列;中文列名“编号、派遣金币、强化经验、孵化秒数”也支持。
- 测试:`python -m unittest discover -s ranch_assistant/tests -v`。
- 122 项测试通过,包含双账号慢网络与大量库存的界面响应、后台账号不重建表格、控件复用、
批量喂养和培育室派遣997的加密HTTP回归;覆盖难度列表解析、扫荡条件/请求顺序/异常暂停/跨角色每日额度、
签到与邮件JSON/空VIP/时间单位/失败不重试、树形规则恢复和截图页不重叠;以及
加密HTTP十连→实际赠蛋→负数空坑孵化→成长结算→派遣→余额刷新、逐种优先级和补货、
多目标喂养优先级、锁定/手动派遣/喂养、开坑与建牧场的费用复核和取消确认、金币/库存/每日额度限制、
购蛋超时记账、突破等级上限、星级筛选、启动/停止/忙时排队和委托奖励显示;也覆盖多账号并行/重启恢复、账号和角色隔离、请求计数持久化、超时恢复、错角色阻止、
右键只读刷新、空值响应显示、心跳、关闭页签,以及四位年份的进入签名、APK 追踪渠道、区服引用还原/去重、两个角色显示、选二区登录、本地错误去重,
Windows 密码加密保存/恢复、登录失败保留密码、调试窗与脱敏日志,
以及 Qt 截图按钮只读、不点击手机、配置恢复、图片变更失效、
设备/分辨率检查、两种区服编号下密码登录及选二区的 loopback HTTP 链路、
缺失/冲突编号停止、Qt 登录回调错误处理、委托、地图和牧场策略;
另覆盖物品分类、赠礼上限/间隔/保留、策略脱敏导入导出及两种退出登录行为。
开发测试未向官方服务提交真实账号凭据,未对真实库存执行购蛋、派遣、喂养、委托或刷图。
用户已验证登录和角色读取;本次买蛋循环及多账号并行由本地模拟服务验证,真实账号效果仍需用户启动后验证。按钮配置需当前页面样本。
- 201 项本地测试通过,覆盖登录、会话隔离、账号关闭与移除、菜单账号路由、数字框滚轮、地图缓存、请求计数、等级与体力结算、成长同步、孵蛋与补货、同种魔物培养与资质提升保护、批量喂养、派遣、赠礼、统一策略配置、委托、扫荡、奖励统计与体力效率和每日奖励。
登录后自动刷新、顶部统一策略开关、关闭策略后继续刷新及多账号批量开关均有回归覆盖。
新增牧场树形/平铺切换、分组数量与空位、刷新保留折叠和控件、4S保留条件、随机刷新间隔及到期独立同步的回归测试。
双账号与大量库存的界面响应继续通过测试;测试使用本地模拟数据和模拟服务,不操作真实账号库存。
- 网络写请求发生异常后不会直接重试,以免重复消耗魔物或物品。
## 委托和扫荡的范围
“自动委托”需单独启用;可先关闭“牧场策略”的自动管理,只运行委托。
“自动委托”需单独启用;可先关闭“自动孵蛋”的自动管理,只运行委托。
道具和魔物提交默认关闭,金币提交上限默认 0;锁定、队伍、高星和高资质保护继续生效。
已接委托需要的魔物种类和蛋会纳入牧场保留。
“也接取需要实战的委托”只允许接取此类任务,当前不会自动导航到每项委托的专用战斗。
@@ -273,17 +261,19 @@
它复用 `stageStart` → `battleEnd` → `recordBattleResult`,无需本地战斗演算或手机截图。
此前只搜索英文 sweep 和中文“扫荡”漏掉了这个拼音方法;现已按该分支实现。
在“地图关卡”展开地区,每关勾选“刷图”、选择难度、输入“本日上限”,再点击“开始扫荡”。
在“自动扫荡”展开地区,每关勾选“刷图”、选择难度、输入“本日上限”,勾选该页功能,再开启顶部策略开关。
星级是服务器通关进度计算出来的,只读。未解锁难度不能选;特殊关卡、未全通关、剧情任务、
体力/金币/门票不足的关卡会显示原因并跳过。次数按角色、日期、关卡和难度保存,
是本地已开始次数,不冒充服务器每日限制。扫荡和ADB实战不能同时运行。
是本地已开始次数,不冒充服务器每日限制。
一次扫荡内部的几个请求顺序执行,完成后重读账号状态;开启其他策略时与孵蛋/委托逐轮串行。
触发随机事件或请求结果不明确时停止,不提交后续结算;在游戏内处理后可清除本地待处理记录。
探索奖励事件由 `stageStart` 返回的 `stageEvent.result` 直接结算,无需提交 `battleEnd`,刷新角色后可继续下一轮。
旧版将此类奖励事件误记为未完成时,只在本地日志能匹配当前角色、关卡和成功响应的情况下自动解除阻塞,不重发请求。
隐藏关卡需要游戏内实战;缺失事件状态或请求结果不明确时保持待处理,避免重复扣体力,在游戏内确认处理后可清除本地记录。
“每日事务”选择要处理的奖励类别,点“领取勾选项目”可立即领取;
点“开始每日事务”会打开统一监控和自动执行,只处理符合状态的项目。
勾选“启用每日奖励领取”并开启顶部策略开关后,只自动处理符合状态的项目。
VIP奖励只对已有资格领取;不会购买VIP或升级礼包。邮件仅领取附件,不删除邮件。
启动/重启默认仍只读,自动化需要手动开始。勾选项、战队、保留体力及刷图规则按角色保存。
启动/重启默认关闭策略,登录后自动刷新并同步到期成长;自动操作由顶部策略开关统一开启。勾选项、战队、保留体力及刷图规则按角色保存。
网络写请求发送前保存本地记录,异常不直接重试;本日已提交但服务器仍返回旧状态的奖励会明确提示。
资料包含此APK的1178个关卡、各难度奖励和2079种道具名称。
+43
View File
@@ -0,0 +1,43 @@
"""Delete one local account workspace without touching sibling accounts."""
from pathlib import Path
import re
import shutil
DEFAULT_ACCOUNT_ENTRIES = ("credentials.json", "credentials.tmp", "sessions", "roles",
"settings.json", "settings.tmp", "purchase_budget.json", "purchase_budget.tmp",
"daily_claims.json", "daily_claims.tmp", "sweep_runs.json", "sweep_runs.tmp",
"maps.json", "maps.tmp", "network_debug.jsonl", "network_debug.previous.jsonl",
"sweep_rewards.sqlite3", "sweep_rewards.sqlite3-journal", "sweep_rewards.sqlite3-wal", "sweep_rewards.sqlite3-shm",
"cultivation_choices.json", "cultivation_choices.tmp")
def profile_directory(root, identifier):
root = Path(root).resolve()
if not isinstance(identifier, str) or not re.fullmatch(r"default|[a-f0-9]{32}", identifier):
raise ValueError("无效的账号工作区编号")
folder = root if identifier == "default" else root / "profiles" / identifier
if folder.resolve() != folder:
raise ValueError("账号工作区包含链接路径,已停止删除")
return folder
def remove_account_files(root, identifier):
"""Caller holds workspace.lock; the legacy default shares the registry root."""
folder = profile_directory(root, identifier)
if not folder.exists():
return
if identifier == "default":
targets = [folder / name for name in DEFAULT_ACCOUNT_ENTRIES if (folder / name).exists() or (folder / name).is_symlink()]
else:
targets = [path for path in folder.iterdir() if path.name != "workspace.lock"]
# Validate the whole deletion set before removing anything. In particular,
# never recursively delete the default root, which contains other accounts.
for path in targets:
if path.resolve().parent != folder or path.is_symlink() or getattr(path, "is_junction", lambda: False)():
raise ValueError("账号记录包含链接路径,已停止删除")
for path in targets:
if path.is_dir():
shutil.rmtree(path)
else:
path.unlink()
+181 -32
View File
@@ -9,6 +9,7 @@ from PySide6 import QtCore as C, QtWidgets as W
from . import gui
from .api import Session
from .sessions import identity
from .account_storage import profile_directory, remove_account_files
class AccountsWindow(W.QMainWindow):
@@ -19,6 +20,7 @@ class AccountsWindow(W.QMainWindow):
self.root.mkdir(parents=True, exist_ok=True)
self.index_path = self.root / "accounts.json"
self.windows, self.locks, self.profiles = {}, {}, []
self.pending_closes, self.pending_removals = set(), set()
self.setWindowTitle("牧羊人之心牧场辅助 — 多账号")
font = self.font()
font.setPointSizeF(8.5)
@@ -27,21 +29,16 @@ class AccountsWindow(W.QMainWindow):
central = W.QWidget()
layout = W.QVBoxLayout(central)
self.setCentralWidget(central)
toolbar = W.QHBoxLayout()
for text, handler in (("新增账号页签", self.add_profile), ("打开已保存账号", self.choose_profile), ("恢复各页签的保存会话", self.resume_all),
("全部开始监控", self.monitor_all), ("全部停止", self.stop_all)):
button = W.QPushButton(text)
button.clicked.connect(handler)
toolbar.addWidget(button)
toolbar.addStretch()
layout.addLayout(toolbar)
note = W.QLabel("每个页签独立登录、保存 Token 和运行。切换页签不会停止其他账号;自动执行需在各账号里分别开启。")
self.setup_menus()
note = W.QLabel("各账号独立登录并持续刷新状态,切换页签不影响其他账号;策略可分别开启或关闭。")
note.setWordWrap(True)
layout.addWidget(note)
self.tabs = W.QTabWidget()
self.tabs.currentChanged.connect(self.activate_profile)
self.tabs.setTabsClosable(True)
self.tabs.tabCloseRequested.connect(self.close_profile)
self.tabs.tabBar().setContextMenuPolicy(C.Qt.ContextMenuPolicy.CustomContextMenu)
self.tabs.tabBar().customContextMenuRequested.connect(self.account_tab_menu)
layout.addWidget(self.tabs, 1)
try:
self.profiles = json.loads(self.index_path.read_text(encoding="utf-8"))["profiles"]
@@ -49,17 +46,76 @@ class AccountsWindow(W.QMainWindow):
self.profiles = [{"id": "default", "label": "账号 1"}]
self.profiles = [p for p in self.profiles if isinstance(p, dict) and re.fullmatch(r"default|[a-f0-9]{32}", str(p.get("id", "")))]
for profile in list(self.profiles):
if profile.get("open", True):
self.open_profile(profile)
if not self.profiles:
self.add_profile()
self.update_account_actions()
gui.compact_layouts(central)
def setup_menus(self):
accounts = self.menuBar().addMenu("账号(&A)")
for text, handler in (("新增账号页签", self.add_profile), ("打开已保存账号…", self.choose_profile),
("恢复各页签的保存会话", self.resume_all)):
accounts.addAction(text, handler)
self.close_account_action = accounts.addAction("关闭当前账号页签", lambda: self.close_profile(self.tabs.currentIndex()))
self.remove_account_action = accounts.addAction("移除当前账号…", self.remove_current_profile)
self.remove_saved_action = accounts.addAction("移除已保存账号…", self.choose_remove_profile)
accounts.aboutToShow.connect(self.update_account_actions)
accounts.addSeparator()
accounts.addAction("退出", self.close)
strategies_run = self.menuBar().addMenu("策略(&R)")
strategies_run.addAction("开启全部账号策略", self.start_all_strategies)
strategies_run.addAction("关闭全部账号策略", self.stop_all)
strategies = self.menuBar().addMenu("策略配置(&S)")
self.save_policy_action = strategies.addAction("保存当前账号策略", self.save_current_policies)
self.save_policy_action.setShortcut("Ctrl+S")
self.import_policy_action = strategies.addAction("导入当前账号策略…",
lambda: self.run_account_action("import_policies"))
self.export_policy_action = strategies.addAction("导出当前账号策略…",
lambda: self.run_account_action("export_policies"))
self.policy_actions = (self.save_policy_action, self.import_policy_action, self.export_policy_action)
strategies.aboutToShow.connect(self.update_account_actions)
help_menu = self.menuBar().addMenu("帮助(&H)")
self.about_action = help_menu.addAction("关于…", self.show_about)
def update_account_actions(self):
window = self.tabs.currentWidget()
for action in self.policy_actions:
action.setEnabled(window is not None and not window.closed)
for action in (self.close_account_action, self.remove_account_action):
action.setEnabled(window is not None and not window.closed)
self.remove_saved_action.setEnabled(bool(self.profiles))
def run_account_action(self, method):
window = self.tabs.currentWidget()
if window is not None and not window.closed:
return getattr(window, method)()
def save_current_policies(self):
value = self.run_account_action("persist_settings")
if value is not None:
label = self.tabs.tabText(self.tabs.currentIndex())
self.statusBar().showMessage(f"已保存账号“{label}”的策略", 5000)
else:
self.statusBar().showMessage("策略尚未保存,请检查当前账号的输入和提示", 5000)
def show_about(self):
W.QMessageBox.about(self, "关于牧羊人之心牧场辅助",
f"牧羊人之心牧场辅助\n\n辅助版本:{gui.APP_VERSION}\n适配游戏版本:{gui.GAME_VERSION}")
def open_profile(self, profile):
identifier = profile["id"]
if not any(p["id"] == identifier for p in self.profiles):
return
if identifier in self.pending_removals:
self.statusBar().showMessage("此账号正在移除,请等待当前请求完成", 5000)
return
if identifier in self.windows:
if self.windows[identifier].closed:
self.statusBar().showMessage("此账号正在关闭,请稍后重新打开", 5000)
return
self.tabs.setCurrentWidget(self.windows[identifier])
return
folder = self.root if identifier == "default" else self.root / "profiles" / identifier
folder = profile_directory(self.root, identifier)
folder.mkdir(parents=True, exist_ok=True)
lock = C.QLockFile(str(folder / "workspace.lock"))
if not lock.tryLock(0):
@@ -68,14 +124,15 @@ class AccountsWindow(W.QMainWindow):
window = gui.Window(folder)
window.connection_guard = lambda session: self.allow_connection(window, session)
window.login_guard = lambda account: self.allow_login(window, account)
window.device_guard = lambda serial: self.allow_device(window, serial)
window.profile_changed.connect(lambda label: self.rename_profile(identifier, label))
self.windows[identifier], self.locks[identifier] = window, lock
self.tabs.addTab(window, profile.get("label", "账号"))
self.tabs.setCurrentWidget(window)
profile["open"] = True
self.save_index()
def add_profile(self):
profile = {"id": uuid.uuid4().hex, "label": f"账号 {len(self.profiles) + 1}"}
profile = {"id": uuid.uuid4().hex, "label": f"账号 {len(self.profiles) + 1}", "open": True}
self.profiles.append(profile)
self.open_profile(profile)
self.save_index()
@@ -84,14 +141,16 @@ class AccountsWindow(W.QMainWindow):
active = self.tabs.currentWidget()
for window in self.windows.values():
window.set_presentation_active(window is active)
self.update_account_actions()
def choose_profile(self):
if not self.profiles:
return
labels = [p.get("label", "账号") + " [" + p["id"][:6] + "]" for p in self.profiles]
profiles = list(self.profiles)
labels = [p.get("label", "账号") + " [" + p["id"][:6] + "]" for p in profiles]
label, accepted = W.QInputDialog.getItem(self, "打开账号页签", "保存的账号工作区", labels, 0, False)
if accepted:
self.open_profile(self.profiles[labels.index(label)])
self.open_profile(profiles[labels.index(label)])
def rename_profile(self, identifier, label):
for profile in self.profiles:
@@ -124,50 +183,137 @@ class AccountsWindow(W.QMainWindow):
return False
return True
def allow_device(self, requester, serial):
return not any(window is not requester and window.farm.running and
(not serial or not window.farm.adb.serial or serial == window.farm.adb.serial) for window in self.windows.values())
def resume_all(self):
for window in self.windows.values():
if window.engine.demo and not window.busy and window.saved_sessions.count():
window.resume_session()
def monitor_all(self):
def start_all_strategies(self):
for window in self.windows.values():
if not window.engine.demo:
window.start_monitor.setChecked(True)
if not window.engine.demo and not window.closed:
window.start_workflow()
def stop_all(self):
for window in self.windows.values():
window.start_monitor.setChecked(False)
window.start_farm.setChecked(False)
window.execute.setChecked(False)
window.stop_workflow()
def close_profile(self, index):
window = self.tabs.widget(index)
if window is None:
return
window.start_monitor.setChecked(False)
window.start_farm.setChecked(False)
identifier = next(k for k, value in self.windows.items() if value is window)
self.close_profile_id(identifier)
def close_profile_id(self, identifier):
window = self.windows.get(identifier)
if window is None:
return
profile = next(p for p in self.profiles if p["id"] == identifier)
if profile.get("open", True):
profile["open"] = False
self.save_index()
window.monitoring = False
window.stop_workflow()
window.timer.stop()
window.hatch_timer.stop()
window.engine.auto = False
window.closed = True
window.pending_refresh = None
window.setEnabled(False)
self.update_account_actions()
if window.busy:
C.QTimer.singleShot(250, lambda: self.close_profile(self.tabs.indexOf(window)))
if identifier not in self.pending_closes:
self.pending_closes.add(identifier)
C.QTimer.singleShot(100, lambda: self.finish_close_profile(identifier))
return
identifier = next(k for k, value in self.windows.items() if value is window)
window.close()
self.tabs.removeTab(index)
self.tabs.removeTab(self.tabs.indexOf(window))
del self.windows[identifier]
self.locks.pop(identifier).unlock()
# Workspaces and saved sessions remain on disk for the next launch.
window.deleteLater()
if identifier in self.pending_removals:
self.finish_remove_profile(identifier)
def finish_close_profile(self, identifier):
self.pending_closes.discard(identifier)
self.close_profile_id(identifier)
def account_tab_menu(self, position):
index = self.tabs.tabBar().tabAt(position)
window = self.tabs.widget(index)
if window is None:
return
identifier = next(k for k, value in self.windows.items() if value is window)
menu = W.QMenu(self)
self.tab_context_menu = menu
menu.addAction("关闭账号页签", lambda: self.close_profile_id(identifier))
menu.addAction("移除此账号…", lambda: self.confirm_remove_profile(identifier))
menu.popup(self.tabs.tabBar().mapToGlobal(position))
def remove_current_profile(self):
window = self.tabs.currentWidget()
if window is not None:
self.confirm_remove_profile(next(k for k, value in self.windows.items() if value is window))
def choose_remove_profile(self):
if not self.profiles:
return
profiles = list(self.profiles)
labels = [p.get("label", "账号") + " [" + p["id"][:6] + "]" for p in profiles]
label, accepted = W.QInputDialog.getItem(self, "移除已保存账号", "选择要移除的账号(含已关闭页签)", labels, 0, False)
if accepted and label:
self.confirm_remove_profile(profiles[labels.index(label)]["id"])
def confirm_remove_profile(self, identifier):
profile = next((p for p in self.profiles if p["id"] == identifier), None)
if profile is None or identifier in self.pending_removals:
return
label = profile.get("label", "账号")
text = f"移除“{label}”?\n\n将删除该账号的本地密码、会话、策略、地图缓存和运行记录,无法恢复。\n此操作不会注销游戏账号。"
if W.QMessageBox.question(self, "移除账号", text, W.QMessageBox.StandardButton.Yes | W.QMessageBox.StandardButton.No,
W.QMessageBox.StandardButton.No) != W.QMessageBox.StandardButton.Yes:
return
self.pending_removals.add(identifier)
if identifier in self.windows:
self.statusBar().showMessage("正在停止该账号,当前请求完成后移除", 5000)
self.close_profile_id(identifier)
else:
self.finish_remove_profile(identifier)
def finish_remove_profile(self, identifier):
lock = None
try:
folder = profile_directory(self.root, identifier)
if folder.exists():
lock = C.QLockFile(str(folder / "workspace.lock"))
if not lock.tryLock(0):
raise ValueError("该账号正在其他窗口使用,请关闭后重试")
remove_account_files(self.root, identifier)
lock.unlock()
lock = None
if identifier != "default":
folder.rmdir()
old_profiles = self.profiles
self.profiles = [p for p in self.profiles if p["id"] != identifier]
try:
self.save_index()
except OSError:
self.profiles = old_profiles
raise
self.statusBar().showMessage("已移除账号及其本地记录", 5000)
except (OSError, ValueError) as error:
self.statusBar().showMessage("账号未完全移除:" + str(error), 10000)
finally:
if lock is not None:
lock.unlock()
self.pending_removals.discard(identifier)
self.update_account_actions()
def closeEvent(self, event):
self.stop_all()
for window in self.windows.values():
window.timer.stop()
window.monitoring = False
window.closed = True
window.pending_refresh = None
if any(window.busy for window in self.windows.values()):
@@ -176,6 +322,9 @@ class AccountsWindow(W.QMainWindow):
C.QTimer.singleShot(250, self.close)
event.ignore()
return
for identifier in list(self.pending_removals):
if identifier in self.windows:
self.close_profile_id(identifier)
for window in self.windows.values():
window.close()
for lock in self.locks.values():
+54 -84
View File
@@ -2,10 +2,10 @@
from PySide6 import QtCore as C, QtWidgets as W
from .daily import DailyPolicy, entries
from .maps import stages
from .native_widgets import IntegerInput, RowBatch
from .presentation import map_source
from .native_widgets import ComboBox, IntegerInput, RowBatch
from .stage_cache import StageCache
from .sweeping import SweepPolicy
from .table_widgets import SORT_ROLE, TreeItem, bind_controls, set_value, table_item
def number(value, maximum=9999):
@@ -27,8 +27,8 @@ class ActivityPages:
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)):
for label, function in (("刷新关卡", self.refresh_maps), ("展开地区", lambda: self.maps_tree.expandAll()),
("折叠地区", lambda: self.maps_tree.collapseAll())):
button = W.QPushButton(label)
button.clicked.connect(function)
line.addWidget(button)
@@ -36,7 +36,7 @@ class ActivityPages:
line = W.QHBoxLayout()
self.map_enabled = W.QCheckBox("启用勾选关卡的自动扫荡")
self.map_keep_ti = number(0)
self.map_team = W.QComboBox()
self.map_team = ComboBox()
for name in ("teamA", "teamB", "teamC"):
self.map_team.addItem(name, name)
line.addWidget(self.map_enabled)
@@ -44,14 +44,9 @@ class ActivityPages:
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.addWidget(reset)
line.addStretch()
layout.addLayout(line)
self.maps_summary = W.QLabel("登录后读取实际解锁状态")
@@ -63,13 +58,15 @@ class ActivityPages:
self.maps_tree.setUniformRowHeights(False)
self.maps_tree.setEditTriggers(W.QAbstractItemView.EditTrigger.NoEditTriggers)
self.maps_tree.itemChanged.connect(self.map_item_changed)
self.maps_tree.sortByColumn(1, C.Qt.SortOrder.AscendingOrder)
self.maps_tree.setSortingEnabled(True)
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 = W.QLabel("地图按账号保存在本地,点击“刷新关卡”才更新列表。星级来自实际通关难度,不能手动修改。\n普通关卡三个难度全部通关后可扫荡;未满足条件的关卡请在游戏内手动战斗。每行勾选、选择难度并输入本日次数上限,使用所选战队。随机掉落并非必得。")
note.setWordWrap(True)
layout.addWidget(note)
self.tabs.addTab(self.map_page, "地图关卡")
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)
@@ -80,25 +77,38 @@ class ActivityPages:
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):
def reset_map_view(self):
if hasattr(self, "map_render_timer"):
self.map_render_timer.stop()
self.maps_tree.clear()
self._map_items, self._map_cities = {}, {}
def refresh_maps(self):
if self.closed:
return
if self.busy:
self.pending_refresh = self.map_page
self.statusBar().showMessage("当前请求完成后刷新关卡")
return
self.submit("map_refresh", self.engine.refresh_stages)
def activity_settings_changed(self, *args):
if self.closed or self.loading_config:
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)
self.settings_changed()
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)
enabled = item.checkState(0) == C.Qt.CheckState.Checked
if self.map_rules.get(key, {}).get("enabled", False) != enabled:
self.map_rule_changed(key, enabled=enabled)
item.setData(0, SORT_ROLE, int(enabled))
def map_rule_changed(self, key, **changes):
self.map_rules[key] = {"enabled": False, "level": "3", "limit": 3} | self.map_rules.get(key, {}) | changes
@@ -113,8 +123,9 @@ class ActivityPages:
if isinstance(focused, W.QLineEdit) and self.maps_tree.isAncestorOf(focused):
return
snapshot = self.engine.snapshot
views = self.prepared_views
all_rows = views.maps if views and views.snapshot is snapshot and views.map_source == map_source(snapshot) else stages(self.catalog, snapshot)
if self.engine.stage_cache.catalog is not self.catalog:
self.engine.stage_cache = StageCache(self.catalog)
all_rows = self.engine.stage_cache.get(snapshot)
grouped = {}
for row in all_rows:
grouped.setdefault(row.stage_id, []).append(row)
@@ -140,7 +151,7 @@ class ActivityPages:
self.map_render_timer = RowBatch(self)
wanted = {row[0] for row in visible}
operations = [("remove", key) for key in self._map_items if key not in wanted] + [("row", row) for row in visible]
first_render = not self.maps_tree.topLevelItemCount()
self.maps_tree.setSortingEnabled(False)
def apply(operation):
kind, data = operation
blocker = C.QSignalBlocker(self.maps_tree)
@@ -152,15 +163,17 @@ class ActivityPages:
first = options[0]
city = self._map_cities.get(first.city)
if city is None:
city = W.QTreeWidgetItem(self.maps_tree, [first.city_name])
city = TreeItem(self.maps_tree, [first.city_name])
city.setFirstColumnSpanned(True)
city.setExpanded(first_render or bool(query))
city.setExpanded(bool(query))
self._map_cities[first.city] = city
elif query:
city.setExpanded(True)
item = self._map_items.get(key)
if item is None:
item = W.QTreeWidgetItem(city)
item = TreeItem(city)
item.setData(0, C.Qt.ItemDataRole.UserRole, key)
difficulty = W.QComboBox()
difficulty = ComboBox()
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))
@@ -172,10 +185,11 @@ class ActivityPages:
str(chosen.stamina) + (" / " + chosen.tickets if chosen.tickets else ""), chosen.drops, "", str(self.engine.sweeper.used(snapshot, chosen))]
for col, text in enumerate(values):
if item.text(col) != text:
item.setText(col, text)
set_value(item, col, text)
if col in (5, 6, 7):
item.setToolTip(col, text)
item.setCheckState(0, C.Qt.CheckState.Checked if rule.get("enabled") else C.Qt.CheckState.Unchecked)
item.setData(0, SORT_ROLE, int(bool(rule.get("enabled"))))
flags = item.flags()
item.setFlags(flags | C.Qt.ItemFlag.ItemIsUserCheckable if any(s.unlocked and s.open for s in options) else flags & ~C.Qt.ItemFlag.ItemIsUserCheckable)
difficulty = self.maps_tree.itemWidget(item, 3)
@@ -188,39 +202,23 @@ class ActivityPages:
for i, stage in enumerate(options):
difficulty.model().item(i).setEnabled(stage.unlocked and stage.open)
difficulty.setCurrentIndex(difficulty.findData(chosen.level))
self.maps_tree.setColumnWidth(3, max(self.maps_tree.columnWidth(3), difficulty.minimumSizeHint().width()))
limit = self.maps_tree.itemWidget(item, 8)
block_limit = C.QSignalBlocker(limit)
if not limit.hasFocus():
limit.setValue(rule.get("limit", 3))
bind_controls(self.maps_tree, item, {3: difficulty, 8: limit})
def finish():
for cid, city in list(self._map_cities.items()):
if not city.childCount():
self.maps_tree.takeTopLevelItem(self.maps_tree.indexOfTopLevelItem(city))
del self._map_cities[cid]
else:
city.sortChildren(1, C.Qt.SortOrder.AscendingOrder)
self.maps_tree.setSortingEnabled(True)
self.map_render_timer.start(operations, apply, finish)
pending = self.engine.sweeper.state.get("pending")
self.maps_summary.setText(f"已解锁 {sum(s.unlocked for s in all_rows)} 个难度;显示 {len(visible)} 关;勾选 {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("已设置手机实战目标;手机需打开该关卡准备页并配置截图")
(" 扫荡策略运行中。" if self.map_enabled.isChecked() and self.strategy_toggle.isChecked() else " 开启顶部策略开关后运行已勾选关卡。"))
def clear_sweep_pending(self):
if self.busy:
@@ -239,7 +237,7 @@ class ActivityPages:
self.daily_page = W.QWidget()
layout = W.QVBoxLayout(self.daily_page)
line = W.QHBoxLayout()
self.daily_enabled = W.QCheckBox("监控时自动领取勾选奖励")
self.daily_enabled = W.QCheckBox("启用每日奖励领取")
line.addWidget(self.daily_enabled)
self.daily_checks = {}
for key, label in (("gift", "每日签到礼包"), ("check", "七日签到"), ("loop", "累计奖励"), ("vip", "VIP日奖"), ("mail", "邮件附件")):
@@ -251,8 +249,7 @@ class ActivityPages:
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))):
for label, function in (("刷新状态", self.refresh), ("领取勾选项目", self.claim_daily)):
button = W.QPushButton(label)
button.clicked.connect(function)
line.addWidget(button)
@@ -266,7 +263,7 @@ class ActivityPages:
self.daily_table.setColumnWidth(0, 280)
self.daily_table.setColumnWidth(1, 230)
layout.addWidget(self.daily_table, 1)
note = W.QLabel("刷新只读取状态。“领取勾选项目”立即处理当前可领奖励;自动领取还需开启监控和“自动执行已启用策略”。邮件仅领取附件。")
note = W.QLabel("刷新只更新状态。“领取勾选项目”立即处理当前可领奖励;勾选此页功能并开启顶部策略开关后,将自动领取。邮件仅领取附件。")
note.setWordWrap(True)
layout.addWidget(note)
self.tabs.addTab(self.daily_page, "每日事务")
@@ -277,12 +274,14 @@ class ActivityPages:
def render_daily(self):
rows = entries(self.catalog, self.engine.snapshot, self.engine.daily_ledger)
self.daily_table.setSortingEnabled(False)
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 = table_item(text, j)
item.setToolTip(text)
self.daily_table.setItem(i, j, item)
self.daily_table.setSortingEnabled(True)
def claim_daily(self):
if self.busy:
@@ -291,32 +290,3 @@ class ActivityPages:
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)
-155
View File
@@ -1,155 +0,0 @@
"""User-triggered page samples, grouped by device, resolution and stage."""
from __future__ import annotations
from datetime import datetime, timedelta, timezone
import hashlib
import json
from pathlib import Path
import re
from PIL import Image
PAGES = (
("stage_ready", "关卡准备页", "需看到关卡名称、选中难度和进入按钮", True),
("battle_start", "战斗倒计时页", "需看到触摸开始 / 开始倒计时", False),
("auto_off", "自动战斗关闭状态", "需看到自动按钮处于关闭状态", False),
("auto_on", "自动战斗开启状态", "需看到自动按钮处于开启状态", False),
("victory", "胜利结算页", "需看到胜利标识和领取 / 继续按钮", True),
("continue", "后续确认页", "胜利后如还有奖励确认 / 返回页面,截取此页", False),
("defeat", "失败结算页", "如方便,保留失败页面以识别停止条件", False),
)
BUTTON_PAGES = {"stage": "stage_ready", "entry": "stage_ready", "countdown": "battle_start",
"auto_off": "auto_off", "victory": "victory", "continue": "continue", "defeat": "defeat"}
def component(value):
return re.sub(r"[^a-zA-Z0-9_.-]", "_", str(value))[:100].strip(".") or "device"
def read_profile(path, root):
path, root = Path(path).resolve(), Path(root).resolve()
if not path.is_relative_to(root):
raise ValueError("截图配置路径不在本地状态目录内")
profile = json.loads(path.read_text(encoding="utf-8"))
if profile.get("schema_version") != 1 or not isinstance(profile.get("captures"), dict):
raise ValueError("无法识别此截图配置")
return profile
def saved_profiles(root, stage_id, level, serial=""):
result = []
for path in (Path(root) / "capture_profiles").glob("*/*/*/profile.json"):
try:
profile = read_profile(path, root)
if (str(profile["stage_id"]) == str(stage_id) and str(profile["stage_level"]) == str(level)
and (not serial or profile["device_serial"] == serial)):
result.append((path.resolve(), profile))
except (OSError, ValueError, KeyError, TypeError):
continue
return sorted(result, key=lambda item: item[0].stat().st_mtime, reverse=True)
def save_page(root, image, serial, stage_id, level, page):
if page not in {p[0] for p in PAGES}:
raise ValueError("未知截图页面")
root = Path(root).resolve()
folder = root / "capture_profiles" / component(serial) / f"{image.width}x{image.height}" / f"{component(stage_id)}_{component(level)}"
folder.mkdir(parents=True, exist_ok=True)
path = folder / "profile.json"
profile = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {
"schema_version": 1, "device_serial": serial, "stage_id": stage_id, "stage_level": str(level),
"resolution": list(image.size), "app_package": "air.net.pixvi.myrzx", "captures": {}}
if (profile["device_serial"] != serial or str(profile["stage_id"]) != str(stage_id)
or profile["stage_level"] != str(level) or profile["resolution"] != list(image.size)):
raise ValueError("截图目录中的设备或关卡记录不一致")
target = folder / (page + ".png")
image.save(target)
profile["captures"][page] = {"file": target.name, "sha256": hashlib.sha256(target.read_bytes()).hexdigest(),
"captured_at": datetime.now(timezone(timedelta(hours=8))).isoformat(timespec="seconds")}
temporary = path.with_suffix(".tmp")
temporary.write_text(json.dumps(profile, ensure_ascii=False, indent=2), encoding="utf-8")
temporary.replace(path)
return path, profile
def write_buttons(profile_path, root, regions):
"""Create templates from regions reviewed by the assistant in saved samples."""
profile_path = Path(profile_path).resolve()
profile = read_profile(profile_path, root)
if not {"stage", "entry", "victory"}.issubset(regions):
raise ValueError("需提供关卡标题、进入和胜利区域")
width, height = profile["resolution"]
templates, sources = {}, {}
for name, region in regions.items():
page = BUTTON_PAGES[name]
record = profile["captures"][page]
source = (profile_path.parent / record["file"]).resolve()
if not source.is_relative_to(Path(root).resolve()) or hashlib.sha256(source.read_bytes()).hexdigest() != record["sha256"]:
raise ValueError("截图文件与记录不一致")
box = list(region["box"])
tap = list(region.get("tap", [(box[0] + box[2]) / 2, (box[1] + box[3]) / 2]))
if (len(box) != 4 or not 0 <= box[0] < box[2] <= width or not 0 <= box[1] < box[3] <= height
or len(tap) != 2 or not 0 <= tap[0] < width or not 0 <= tap[1] < height):
raise ValueError("按钮区域或点击位置超出截图范围")
filename = f"button_{name}.png"
with Image.open(source) as image:
image.crop(box).save(profile_path.parent / filename)
templates[name] = {"file": filename, "box": box, "tap": tap}
sources[page] = record["sha256"]
buttons = {k: profile[k] for k in ("schema_version", "device_serial", "stage_id", "stage_level", "resolution")}
buttons.update(source_captures=sources, templates=templates)
path = profile_path.with_name("buttons.json")
temporary = path.with_suffix(".tmp")
temporary.write_text(json.dumps(buttons, ensure_ascii=False, indent=2), encoding="utf-8")
temporary.replace(path)
load_buttons(profile_path, root, profile["stage_id"], profile["stage_level"])
return path
def load_buttons(profile_path, root, stage_id, level, serial=""):
profile_path, root = Path(profile_path).resolve(), Path(root).resolve()
profile = read_profile(profile_path, root)
path = profile_path.with_name("buttons.json")
buttons = json.loads(path.read_text(encoding="utf-8"))
if str(buttons["stage_id"]) != str(stage_id) or str(buttons["stage_level"]) != str(level):
raise ValueError("按钮配置与所选关卡/难度不一致")
if str(profile["stage_id"]) != str(stage_id) or str(profile["stage_level"]) != str(level):
raise ValueError("页面截图属于其他关卡或难度")
if buttons["resolution"] != profile["resolution"] or buttons.get("device_serial") != profile["device_serial"]:
raise ValueError("按钮配置与当前设备或分辨率不一致")
if serial and profile["device_serial"] != serial:
raise ValueError("按钮配置属于其他设备")
sources = buttons.get("source_captures", {})
if not sources or any(profile["captures"].get(k, {}).get("sha256") != v for k, v in sources.items()):
raise ValueError("页面截图已更新,需要重新生成按钮配置")
if not {"stage_ready", "victory"}.issubset(sources):
raise ValueError("按钮配置缺少必需页面来源")
for key, digest in sources.items():
source = (path.parent / profile["captures"][key]["file"]).resolve()
if not source.is_relative_to(root) or hashlib.sha256(source.read_bytes()).hexdigest() != digest:
raise ValueError("截图文件与记录不一致,请重新截图并生成配置")
templates = {}
for name, original in buttons.get("templates", {}).items():
item = dict(original)
image_path = (path.parent / item["file"]).resolve()
if not image_path.is_relative_to(root) or not image_path.is_file():
raise ValueError("按钮模板图片缺失或路径无效")
item["file"] = str(image_path.relative_to(root))
item["stage_id"], item["stage_level"] = str(stage_id), str(level)
item["screen"] = buttons["resolution"]
item["device_serial"] = profile["device_serial"]
item["strict_resolution"] = True
width, height = buttons["resolution"]
box = item.get("box", [])
if (len(box) != 4 or not 0 <= box[0] < box[2] <= width or not 0 <= box[1] < box[3] <= height):
raise ValueError("按钮识别区域超出截图范围")
tap = item.get("tap", [(box[0] + box[2]) / 2, (box[1] + box[3]) / 2])
if len(tap) != 2 or not 0 <= tap[0] < width or not 0 <= tap[1] < height:
raise ValueError("按钮点击位置超出截图范围")
with Image.open(image_path) as reference:
if reference.size != (box[2] - box[0], box[3] - box[1]):
raise ValueError("按钮模板尺寸与识别区域不一致")
templates[name] = item
if not {"stage", "entry", "victory"}.issubset(templates):
raise ValueError("按钮配置缺少关卡名称、进入或胜利模板")
return templates
+77
View File
@@ -0,0 +1,77 @@
"""Choose a single ranch representative per species, independently of gifts."""
import json
from pathlib import Path
import random
import threading
def growth_values(catalog, mon):
if any(value is None for value in catalog.quality(mon)):
return None
row = catalog.monster(mon.get("typeId"))
return tuple(round(min(1, max(0, (float(f"{float(mon['g' + stat.capitalize()]):.3f}")
- row[stat + "_grow_min"]) / (row[stat + "_grow_max"] - row[stat + "_grow_min"]))), 9)
for stat in ("atk", "def", "hp", "dex"))
def growth_score(catalog, mon):
values = growth_values(catalog, mon)
return round(sum(values) / 4, 9) if values is not None else None
class CultivationSelector:
def __init__(self, catalog, path=None):
self.catalog = catalog
self.path = Path(path) if path else None
self.owner = None
self.choices = {}
self.selected = {}
self.signature = None
self.lock = threading.RLock()
def rank(self, mon):
values = growth_values(self.catalog, mon)
return (int(mon.get("level") or 1), int(mon.get("feel") or 0),
round(sum(values) / 4, 9) if values is not None else -1,
values if values is not None else (-1,) * 4)
def select(self, snapshot):
with self.lock:
owner = str(snapshot.raw["master"]["id"])
ranch = [mon for mon in snapshot.raw["monsters"] if mon.get("process") == 3 and mon.get("typeId") is not None]
signature = (owner, tuple((int(mon["id"]), str(mon["typeId"]), mon.get("level"), mon.get("feel"),
*(mon.get(key) for key in ("gAtk", "gDef", "gHp", "gDex"))) for mon in ranch))
if self.signature == signature:
current = {int(mon["id"]): mon for mon in ranch}
self.selected = {key: current[int(mon["id"])] for key, mon in self.selected.items()}
return self.selected
if self.owner != owner:
self.choices = {}
if self.path and self.path.exists():
try:
value = json.loads(self.path.read_text(encoding="utf-8"))
if value.get("owner") == owner and isinstance(value.get("choices"), dict):
self.choices = {str(key): int(mid) for key, mid in value["choices"].items()}
except (OSError, ValueError, TypeError, AttributeError):
pass
self.owner = owner
groups = {}
for mon in ranch:
groups.setdefault(str(mon["typeId"]), []).append(mon)
selected = {}
for key, members in groups.items():
ranked = [(self.rank(mon), mon) for mon in members]
highest = max(rank for rank, _ in ranked)
tied = [mon for rank, mon in ranked if rank == highest]
previous = next((mon for mon in tied if int(mon["id"]) == self.choices.get(key)), None)
selected[key] = previous if previous is not None else tied[0] if len(tied) == 1 else random.choice(tied)
choices = {key: int(mon["id"]) for key, mon in selected.items()}
if choices != self.choices:
if self.path:
self.path.parent.mkdir(parents=True, exist_ok=True)
temporary = self.path.with_suffix(".tmp")
temporary.write_text(json.dumps({"owner": owner, "choices": choices}, ensure_ascii=False), encoding="utf-8")
temporary.replace(self.path)
self.choices = choices
self.signature, self.selected = signature, selected
return selected
File diff suppressed because one or more lines are too long
+2 -1
View File
@@ -2,6 +2,7 @@
import json
from pathlib import Path
from PySide6 import QtCore as C, QtGui as G, QtWidgets as W
from .table_widgets import table_item
class DebugWindow(W.QDialog):
@@ -51,7 +52,7 @@ class DebugWindow(W.QDialog):
if event["kind"] == "error" and event.get("scope") == "local":
values[2] = "本地错误"
for index, value in enumerate(values):
self.rows.setItem(row, index, W.QTableWidgetItem(str(value)))
self.rows.setItem(row, index, table_item(value, index))
# Follow the newest record unless the user is inspecting an older row.
if row == 0 or self.rows.currentRow() in (-1, row - 1) or event["kind"] == "error":
self.rows.selectRow(row)
+293
View File
@@ -0,0 +1,293 @@
"""Confirmed sweep rewards and empirical drop rates, stored only locally."""
from contextlib import contextmanager
from datetime import datetime
import json
import math
from pathlib import Path
import sqlite3
import threading
import weakref
def event_reward(response):
event = response.get("stageEvent")
if (response.get("triggerEvent") in (True, 1) and isinstance(event, dict)
and event.get("resCode", 0) in (0, "0") and event.get("hideStageId") is None
and isinstance(event.get("result"), dict)):
return event["result"]
def drop_info(catalog, type_id, kind="item"):
key = str(type_id)
if kind == "item" and key in catalog.monsters:
kind = "egg"
if kind in ("egg", "monster"):
name = catalog.monster(key).get("name", key) + ("蛋" if kind == "egg" else "")
else:
name = catalog.data.get("item_names", {}).get(key, f"物品 #{key}")
return {"key": f"{kind}:{key}", "typeId": key, "kind": kind, "name": name}
def integer(value):
if type(value) not in (int, float) or not math.isfinite(value) or int(value) != value:
raise ValueError("奖励数量不是有效整数")
return int(value)
def normalize_reward(catalog, reward):
if not isinstance(reward, dict):
raise ValueError("结算响应缺少奖励对象")
result = {key: integer(reward.get(key) or 0) for key in ("money", "exp", "ke", "ti")}
drops = {}
for field, kind in (("items", "item"), ("monsters", "monster")):
rows = reward.get(field) or []
if not isinstance(rows, list):
raise ValueError("结算奖励列表格式错误")
for row in rows:
if not isinstance(row, dict):
raise ValueError("结算奖励条目格式错误")
type_id = row.get("typeId", row.get("type"))
if type_id is None:
raise ValueError("结算奖励缺少物品编号")
number = integer(row.get("num", 1) if kind == "monster" else row.get("num"))
if number < 0:
raise ValueError("奖励物品数量不能为负数")
if not number:
continue
info = drop_info(catalog, type_id, kind)
entry = drops.setdefault(info["key"], info | {"num": 0})
entry["num"] += number
result["drops"] = list(drops.values())
return result
def reward_text(reward):
if reward is None:
return "奖励数据未确认,未计入统计"
parts = [f"{label} {reward[key]}" for key, label in (("money", "金币"), ("exp", "经验"), ("ke", "氪金"), ("ti", "体力")) if reward[key]]
parts.extend(f"{row['name']} ×{row['num']}" for row in reward["drops"])
return ";".join(parts) or "无物品或货币奖励"
def log_events(path):
with path.open(encoding="utf-8") as stream:
for line in stream:
try:
value = json.loads(line)
except ValueError:
continue
if isinstance(value, dict):
yield value
def possible_drops(catalog, stage_id, level):
reward = catalog.data.get("stage_info", {}).get(stage_id, {}).get("level", {}).get(str(level), {}).get("reward") or {}
found = {}
for piece in reward.get("rewards") or []:
if piece.get("num", 0) > 0 and piece.get("chance", 1) > 0:
for row in piece.get("monsters") or []:
info = drop_info(catalog, row["name"], "monster" if piece.get("monMode") else "egg")
found[info["key"]] = info
if piece.get("item_num", 0) > 0 and piece.get("item_chance", 1) > 0:
for row in piece.get("items") or []:
info = drop_info(catalog, str(row["name"]).split(",")[0])
found[info["key"]] = info
return found
def interval(hits, samples):
if not samples:
return None
z = 1.95996398454
rate = hits / samples
denominator = 1 + z * z / samples
center = (rate + z * z / (2 * samples)) / denominator
radius = z * math.sqrt(rate * (1 - rate) / samples + z * z / (4 * samples * samples)) / denominator
return max(0, center - radius), min(1, center + radius)
def analyze(catalog, data, stage_id, level, source="sweep"):
kinds = ("sweep", "event") if source == "all" else (source,)
totals = {"n": 0, "money": 0, "exp": 0, "ke": 0, "ti": 0, "spent": 0, "known": 0}
known = possible_drops(catalog, stage_id, level)
rows = {key: info | {"hits": 0, "units": 0, "cost_units": 0, "configured": True} for key, info in known.items()}
for kind in kinds:
key = f"{stage_id}:{level}:{kind}"
total = data.get("totals", {}).get(key, {})
for field in totals:
totals[field] += total.get(field, 0)
for row in data.get("drops", {}).get(key, []):
target = rows.setdefault(row["key"], {k: row[k] for k in ("key", "typeId", "kind", "name")} | {"hits": 0, "units": 0, "cost_units": 0, "configured": False})
target["hits"] += row["hits"]
target["units"] += row["units"]
target["cost_units"] += row.get("cost_units", 0)
for row in rows.values():
row.update(samples=totals["n"], rate=row["hits"] / totals["n"] if totals["n"] else None,
average=row["units"] / totals["n"] if totals["n"] else None, interval=interval(row["hits"], totals["n"]),
per_stamina=row["cost_units"] / totals["spent"] if totals["spent"] else None)
return totals, sorted(rows.values(), key=lambda row: (-(row["rate"] or 0), row["name"]))
SCHEMA = """
CREATE TABLE IF NOT EXISTS samples (
owner TEXT, source TEXT, stage TEXT, level TEXT, kind TEXT, timestamp REAL, reward TEXT,
PRIMARY KEY(owner, source));
CREATE TABLE IF NOT EXISTS totals (
owner TEXT, stage TEXT, level TEXT, kind TEXT, n INTEGER, money INTEGER, exp INTEGER,
ke INTEGER, ti INTEGER, spent INTEGER, known INTEGER DEFAULT 0, PRIMARY KEY(owner,stage,level,kind));
CREATE TABLE IF NOT EXISTS drops (
owner TEXT, stage TEXT, level TEXT, kind TEXT, key TEXT, typeId TEXT, category TEXT,
name TEXT, hits INTEGER, units INTEGER, cost_units INTEGER DEFAULT 0, PRIMARY KEY(owner,stage,level,kind,key));
CREATE TABLE IF NOT EXISTS metadata (key TEXT PRIMARY KEY, value TEXT);
"""
class SweepStatistics:
def __init__(self, catalog, path=None):
self.catalog = catalog
self.path = Path(path) if path else None
self.lock = threading.RLock()
self.memory = None
self.memo = None
self.backfilled = set()
self.error = ""
self.schema_ready = False
@contextmanager
def connection(self, write=False):
with self.lock:
if self.path:
if not write and not self.path.exists():
yield None
return
if write:
self.path.parent.mkdir(parents=True, exist_ok=True)
connection = sqlite3.connect(str(self.path), timeout=1)
else:
if self.memory is None:
if not write:
yield None
return
self.memory = sqlite3.connect(":memory:", check_same_thread=False)
self.memory_cleanup = weakref.finalize(self, self.memory.close)
connection = self.memory
connection.row_factory = sqlite3.Row
try:
if not self.schema_ready:
connection.executescript(SCHEMA)
if "known" not in {row["name"] for row in connection.execute("PRAGMA table_info(totals)")}:
connection.execute("ALTER TABLE totals ADD COLUMN known INTEGER DEFAULT 0")
connection.execute("UPDATE totals SET spent=0")
if "cost_units" not in {row["name"] for row in connection.execute("PRAGMA table_info(drops)")}:
connection.execute("ALTER TABLE drops ADD COLUMN cost_units INTEGER DEFAULT 0")
connection.commit()
self.schema_ready = True
with connection:
yield connection
finally:
if self.path:
connection.close()
def record(self, owner, stage, level, kind, source, timestamp, reward, spent=None):
with self.connection(write=True) as db:
added = self.insert_record(db, owner, stage, level, kind, source, timestamp, reward, spent)
if added:
self.memo = None
return added
def insert_record(self, db, owner, stage, level, kind, source, timestamp, reward, spent=None):
if kind not in ("sweep", "event"):
raise ValueError("未知的结算类型")
normalized = normalize_reward(self.catalog, reward)
cost = integer(spent) if spent is not None else None
if cost is not None and cost < 0:
cost = None
result = db.execute("INSERT OR IGNORE INTO samples VALUES(?,?,?,?,?,?,?)",
(str(owner), source, stage, str(level), kind, timestamp, json.dumps(normalized | {"spent": cost}, ensure_ascii=False)))
if result.rowcount == 0:
return False
db.execute("""INSERT INTO totals(owner,stage,level,kind,n,money,exp,ke,ti,spent,known) VALUES(?,?,?,?,1,?,?,?,?,?,?)
ON CONFLICT(owner,stage,level,kind) DO UPDATE SET n=n+1,
money=money+excluded.money, exp=exp+excluded.exp, ke=ke+excluded.ke,
ti=ti+excluded.ti, spent=spent+excluded.spent, known=known+excluded.known""",
(str(owner), stage, str(level), kind, normalized["money"], normalized["exp"], normalized["ke"], normalized["ti"], cost or 0, int(cost is not None)))
for row in normalized["drops"]:
db.execute("""INSERT INTO drops(owner,stage,level,kind,key,typeId,category,name,hits,units,cost_units) VALUES(?,?,?,?,?,?,?,?,1,?,?)
ON CONFLICT(owner,stage,level,kind,key) DO UPDATE SET hits=hits+1, units=units+excluded.units, cost_units=cost_units+excluded.cost_units""",
(str(owner), stage, str(level), kind, row["key"], row["typeId"], row["kind"], row["name"], row["num"], row["num"] if cost is not None else 0))
return True
def snapshot(self, owner):
owner = str(owner)
if self.memo and self.memo["owner"] == owner:
return self.memo
data = {"owner": owner, "totals": {}, "drops": {}, "error": self.error}
try:
with self.connection() as db:
if db:
for row in db.execute("SELECT * FROM totals WHERE owner=?", (owner,)):
key = f"{row['stage']}:{row['level']}:{row['kind']}"
data["totals"][key] = {field: row[field] for field in ("n", "money", "exp", "ke", "ti", "spent", "known")}
for row in db.execute("SELECT * FROM drops WHERE owner=?", (owner,)):
key = f"{row['stage']}:{row['level']}:{row['kind']}"
data["drops"].setdefault(key, []).append({field: row[field] for field in ("key", "typeId", "name", "hits", "units", "cost_units")} | {"kind": row["category"]})
except (sqlite3.Error, OSError) as error:
data["error"] = "本地统计读取失败:" + str(error)
self.memo = data
return data
def import_log(self, owner, trace_path):
"""Import only role-matched successful helper settlements, once per role."""
owner = str(owner)
if owner in self.backfilled or not trace_path:
return
self.backfilled.add(owner)
try:
with self.connection() as db:
if db and db.execute("SELECT 1 FROM metadata WHERE key=?", ("backfill:" + owner,)).fetchone():
return
requests, role, samples = {}, None, []
path = Path(trace_path)
for file in (path.with_name("network_debug.previous.jsonl"), path):
if not file.exists():
continue
for event in log_events(file):
body = event.get("body")
if not isinstance(body, dict):
continue
operation, direction = event.get("operation"), event.get("kind")
if operation == "读取角色" and direction == "response":
role = str((body.get("master") or {}).get("id"))
identifier = event.get("request_id")
if not identifier:
continue
if direction == "request" and role == owner:
if operation == "stageService/stageStart":
requests[identifier] = ("event", body.get("stageTypeId"), body.get("stageLevel"))
elif operation == "battleService/battleEnd":
battle = body.get("battleData") or {}
position = battle.get("battlePosition") or {}
if (battle.get("win") is True and position.get("battleType") == "stage"
and all(battle.get(key) == 0 for key in ("leftTime", "killNum", "totalDamage", "cheatNum"))):
requests[identifier] = ("sweep", position.get("stageId"), position.get("stageLevel"))
elif direction == "response" and identifier in requests and event.get("http_status") == 200 and body.get("resCode") in (0, "0"):
kind, stage, level = requests.pop(identifier)
reward = event_reward(body) if kind == "event" else body.get("reward")
if isinstance(reward, dict) and stage in self.catalog.data["stage_info"] and str(level) in self.catalog.data["stage_info"][stage]["level"]:
try:
timestamp = datetime.fromisoformat(event["time"]).timestamp()
cost = (body.get("stageEvent") or {}).get("costTi") if kind == "event" else body.get("costTi")
samples.append((owner, stage, level, kind, "request:" + identifier, timestamp, reward, cost))
except (ValueError, TypeError, KeyError):
continue
with self.connection(write=True) as db:
for sample in samples:
try:
self.insert_record(db, *sample)
except (ValueError, TypeError, KeyError):
continue
db.execute("INSERT OR REPLACE INTO metadata VALUES(?,?)", ("backfill:" + owner, "1"))
self.memo = None
except (sqlite3.Error, OSError, AttributeError, TypeError) as error:
self.error = "历史日志补录未完成:" + str(error)
self.memo = None
+17 -9
View File
@@ -3,7 +3,8 @@ import copy
from dataclasses import asdict
from PySide6 import QtCore as C, QtWidgets as W
from .model import EggRule, duration
from .native_widgets import IntegerInput, RowBatch
from .native_widgets import ComboBox, IntegerInput, RowBatch
from .table_widgets import CenteredCheckBox, bind_controls, set_value, table_item
class EggTable(W.QTableWidget):
@@ -20,7 +21,7 @@ class EggTable(W.QTableWidget):
self.setEditTriggers(W.QAbstractItemView.EditTrigger.NoEditTriggers)
self.setSelectionBehavior(W.QAbstractItemView.SelectionBehavior.SelectRows)
self.horizontalHeader().setSectionResizeMode(W.QHeaderView.ResizeMode.Interactive)
for column, width in enumerate((130, 45, 65, 65, 90, 95, 95, 95, 160, 95, 90, 90, 100, 100, 160)):
for column, width in enumerate((130, 45, 65, 65, 90, 135, 95, 95, 220, 95, 90, 90, 100, 100, 160)):
self.setColumnWidth(column, width)
self.verticalHeader().setDefaultSectionSize(24)
@@ -60,12 +61,17 @@ class EggTable(W.QTableWidget):
values = [data.get("name", key), data.get("star", "?"), group["count"], "", "", "", "", "", "",
duration(total), money, exp, round(money * 3600 / total, 2), round(exp * 3600 / total, 2), ", ".join(group["ids"])]
for j, value in enumerate(values):
item = W.QTableWidgetItem()
item.setData(C.Qt.ItemDataRole.DisplayRole, value)
item = self.item(i, j)
if item is None:
item = table_item(value, j)
self.setItem(i, j, item)
else:
set_value(item, j, value)
if j == 1:
item.setTextAlignment(C.Qt.AlignmentFlag.AlignCenter)
if j == 0:
item.setData(C.Qt.ItemDataRole.UserRole, key)
item.setToolTip(f"魔物编号 {key}")
self.setItem(i, j, item)
existing = self.cellWidget(i, 3)
if existing and existing.property("egg_type_id") == key:
controls = [self.cellWidget(i, col) for col in range(3, 9)]
@@ -76,8 +82,9 @@ class EggTable(W.QTableWidget):
control.setValue(rule[field])
controls[2].setCurrentIndex(max(0, controls[2].findData(rule["action"])))
controls[5].setCurrentIndex(max(0, controls[5].findData(rule["market_id"])))
bind_controls(self, i, dict(zip(range(3, 9), controls)))
return
enabled = W.QCheckBox()
enabled = CenteredCheckBox()
enabled.setProperty("egg_type_id", key)
enabled.setChecked(rule["enabled"])
priority, below, target = IntegerInput(), IntegerInput(), IntegerInput()
@@ -85,11 +92,10 @@ class EggTable(W.QTableWidget):
(target, max(1, rule["refill_below"]), 1000, rule["refill_target"])):
control.setRange(low, high)
control.setValue(value)
control.setFixedWidth(76)
priority.setToolTip("数字越小,孵化优先级越高")
below.setToolTip("可用蛋少于此数量时补货;0表示不自动补货")
target.setToolTip("补货希望达到的可用蛋数量;市场随机出蛋,实际结果由服务器决定")
action, market = W.QComboBox(), W.QComboBox()
action, market = ComboBox(), ComboBox()
for name, value in (("派遣", "sell"), ("喂养", "feed"), ("保留", "keep")):
action.addItem(name, value)
action.setCurrentIndex(max(0, action.findData(rule["action"])))
@@ -99,7 +105,8 @@ class EggTable(W.QTableWidget):
if not market.count():
market.addItem("金币市场无此蛋", "")
market.setCurrentIndex(max(0, market.findData(rule["market_id"])))
market.setMaximumWidth(135)
self.setColumnWidth(5, max(self.columnWidth(5), action.minimumSizeHint().width()))
self.setColumnWidth(8, max(self.columnWidth(8), market.minimumSizeHint().width()))
controls = {"enabled": enabled, "priority": priority, "action": action, "refill_below": below,
"refill_target": target, "market_id": market}
for column, control in zip(range(3, 9), controls.values()):
@@ -118,6 +125,7 @@ class EggTable(W.QTableWidget):
control.valueChanged.connect(commit)
action.currentIndexChanged.connect(commit)
market.currentIndexChanged.connect(commit)
bind_controls(self, i, dict(zip(range(3, 9), controls.values())))
def finish():
self.setSortingEnabled(True)
self.updating = False
+75 -19
View File
@@ -10,13 +10,21 @@ from .quests import QuestPolicy, TaskPlanner
from .market import PurchaseBudget
from .management import expansion_quote, manual_monster_actions
from .gifts import GiftPlanner
from .master_sync import MasterSync
from .stage_cache import StageCache
from .drop_statistics import reward_text
from .cultivation import CultivationSelector
class Engine:
def __init__(self, catalog, client=None, budget_path=None):
self.catalog, self.client = catalog, client
self.planner = Planner(catalog)
self.gift_planner = GiftPlanner(catalog)
folder = Path(budget_path).parent if budget_path else None
self.cultivation = CultivationSelector(catalog, folder / "cultivation_choices.json" if folder else None)
self.planner = Planner(catalog, self.cultivation)
self.hatch_planner = Planner(catalog, self.cultivation)
self.pending_hatches = []
self.gift_planner = GiftPlanner(catalog, self.cultivation)
self.policy = Policy()
self.quest_policy = QuestPolicy()
self.tasks = TaskPlanner(catalog)
@@ -29,15 +37,19 @@ class Engine:
self.last_draw = ""
self.growth_cache = {}
self.growth_attempts = {}
self.master_sync = MasterSync(catalog)
self.last_executed = False
folder = Path(budget_path).parent if budget_path else None
self.stage_cache = StageCache(catalog, folder / "maps.json" if folder 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, *, sync_master=True):
self.snapshot = self.client.snapshot()
self.master_sync.apply(self.snapshot)
if sync_master:
self.master_sync.settle(self.client, self.snapshot)
present = self.snapshot.monsters
self.growth_cache = {mid: entry for mid, entry in self.growth_cache.items() if mid in present}
self.growth_attempts = {key: stamp for key, stamp in self.growth_attempts.items() if key[0] in present}
@@ -65,8 +77,25 @@ class Engine:
mon.update({field: entry[field] for field in fields if field in entry})
rows.append(mon)
self.snapshot.raw["monsters"] = rows
self.sweeper.recover_reward_event(self.snapshot, getattr(getattr(self.client, "trace", None), "path", None))
return self.snapshot
def master_sync_due(self):
return not self.demo and bool(self.master_sync.pending(self.snapshot))
def sync_master(self):
self.read_snapshot()
return self.snapshot, self.plans(), "已同步等级 / 体力"
def refresh_stages(self):
self.auto = False
if not self.demo:
self.read_snapshot()
elif self.snapshot is None:
self.snapshot = demo_snapshot(self.catalog)
self.stage_cache.get(self.snapshot, refresh=True)
return self.snapshot, self.plans(), "已刷新关卡并保存当前账号的地图缓存"
def remember_growth(self, response):
# MonsterCenter.checkGrowUpHandler treats these two arrays as the
# authoritative stage and growth values, including after a stale read.
@@ -99,8 +128,13 @@ class Engine:
self.read_snapshot()
return True
def growth_sync_due(self):
if self.snapshot is None:
return False
now = time.monotonic()
return any(now - self.growth_attempts.get(key, -1e12) >= 60 for key in self.snapshot.growth_pending(self.catalog))
def sync_growth(self):
self.auto = False
if self.demo:
if self.snapshot is None:
self.snapshot = demo_snapshot(self.catalog)
@@ -109,9 +143,9 @@ class Engine:
mon["mode"] = self.snapshot.expected_growth_mode(mon, self.catalog)
else:
self.read_snapshot()
self.settle_pending_growth(force=True)
self.settle_pending_growth()
pending = self.snapshot.growth_pending(self.catalog)
message = "已同步孵化 / 成长状态;本次不执行派遣或喂养"
message = "已自动同步孵化 / 成长状态"
if pending:
message += f";仍有 {len(pending)} 只等待服务器确认阶段或资质"
return self.snapshot, self.plans(), message
@@ -123,30 +157,35 @@ class Engine:
self.client.call("heartBeatService/keepAlive")
return "会话心跳已更新"
def poll(self):
def poll(self, *, hatch_only=False, defer_hatch=False):
self.last_executed = False
settled = False
if self.demo:
if self.snapshot is None:
self.snapshot = demo_snapshot(self.catalog)
if self.auto and self.policy.enabled:
for mon in self.snapshot.raw["monsters"]:
if mon.get("process") == 2:
mon["mode"] = self.snapshot.expected_growth_mode(mon, self.catalog)
else:
self.read_snapshot()
if self.auto and self.policy.enabled:
self.read_snapshot(sync_master=not hatch_only)
if not hatch_only:
settled = self.settle_pending_growth()
message = "状态已刷新" + (";已请求孵化 / 成长结算" if settled else "")
if not self.auto and self.snapshot.growth_pending(self.catalog):
message += ";仅监控:有待结算的孵化 / 成长;请开始执行,或点击“同步孵化 / 成长”"
if self.sweeper.recovered_event:
message += ";已解除旧版对已结算奖励事件的误阻塞"
self.sweeper.recovered_event = False
if self.snapshot.growth_pending(self.catalog):
message += ";成长状态等待服务器确认,将自动检查"
try:
plans = self.plans()
except (ValueError, TypeError, KeyError, AttributeError) as error:
self.auto = False
return self.snapshot, [], "状态已读取;策略暂不可用:" + str(error)
if self.auto and plans:
action = plans[0]
actions = self.pending_hatches if hatch_only else plans
action = actions[0] if actions else None
if action and defer_hatch and action.kind == "hatch":
action = None
if self.auto and action is not None:
self.last_executed = True
if action.kind == "daily":
entry = next(row for row in selected_entries(self.catalog, self.snapshot, self.daily_policy, self.daily_ledger) if row.action == action)
@@ -156,9 +195,13 @@ class Engine:
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)
result = 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}"
label = "探索奖励事件已结算" if self.sweeper.last_outcome == "event" else "扫荡完成"
message = f"{label}:{stage.number} {stage.name} / 难度{stage.level};" + reward_text(self.sweeper.last_reward)
if self.sweeper.statistics_error:
message += ";" + self.sweeper.statistics_error
return self.snapshot, self.plans(), message
if action.kind == "buy":
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)
@@ -168,7 +211,13 @@ class Engine:
response = self.client.call(action.path, action.payload)
if action.kind == "buy":
self.record_draw(response.get("eggs") or [])
self.read_snapshot()
self.read_snapshot(sync_master=not hatch_only)
if action.kind == "hatch":
stack_id = action.payload["eggs"][0]["stackId"]
slot = next((slot for slot in self.snapshot.raw["stacks"] if int(slot["id"]) == stack_id), None)
if slot is None or int(slot.get("monsterId") or 0) <= 0:
self.auto = False
raise ValueError("装填已返回,但坑位状态尚未同步;已停止,请刷新核对后再继续")
if action.kind == "feed" and any(mid in self.snapshot.monsters for mid in action.payload["foods"]):
self.auto = False
raise ValueError("喂养已返回,但素材状态尚未同步;已停止,请刷新核对后再继续")
@@ -186,17 +235,24 @@ class Engine:
return self.snapshot, plans, message
def plans(self):
if self.policy.keep_better_quality or self.policy.gift_auto_representative:
self.cultivation.select(self.snapshot)
quests = self.tasks.plan(self.snapshot, self.quest_policy, self.policy)
types, eggs = self.tasks.reservations(self.snapshot)
reserved = dict(self.policy.reserved_eggs)
for key, count in eggs.items():
reserved[key] = max(reserved.get(key, 0), count)
policy = replace(self.policy, reserved_types=list(set(self.policy.reserved_types) | types), reserved_eggs=reserved)
self.hatch_planner.notes = []
self.pending_hatches = self.hatch_planner.hatch_actions(self.snapshot, policy)
left = self.purchase_budget.remaining(self.snapshot.now, policy.daily_buy_money)
daily = [row.action for row in selected_entries(self.catalog, self.snapshot, self.daily_policy, self.daily_ledger)] if self.daily_policy.enabled else []
sweep = self.sweeper.next(self.snapshot, self.sweep_policy) if self.sweep_policy.enabled and not self.demo else None
sweep_actions = [Action(kind="sweep", path="", payload={}, description=f"扫荡 {sweep.number} {sweep.name} / 难度{sweep.level}")] if sweep else []
return daily + quests + self.gift_planner.plan(self.snapshot, policy, self.quest_policy) + self.planner.plan(self.snapshot, policy, left) + sweep_actions
gifts = self.gift_planner.plan(self.snapshot, policy, self.quest_policy)
ranch = self.planner.plan(self.snapshot, policy, left)
self.planner.notes.extend(self.gift_planner.notes)
return daily + quests + gifts + ranch + sweep_actions
def claim_daily_entry(self, entry):
self.daily_ledger.record(self.snapshot, entry.key)
-199
View File
@@ -1,199 +0,0 @@
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
import io
import json
from pathlib import Path
import shutil
import subprocess
import time
from PIL import Image, ImageChops, ImageStat
from .capture import load_buttons
class Adb:
def __init__(self, executable="", serial=""):
self.executable = executable or shutil.which("adb") or r"C:\Program Files\adb_tools\adb.exe"
self.serial = serial
def run(self, *args, binary=False):
command = [self.executable] + (["-s", self.serial] if self.serial else []) + list(args)
flags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
result = subprocess.run(command, capture_output=True, timeout=12, creationflags=flags)
if result.returncode:
raise RuntimeError("ADB 操作失败,请检查连接、授权和设备编号")
return result.stdout if binary else result.stdout.decode("utf-8", errors="replace")
def screenshot(self):
raw = self.run("exec-out", "screencap", "-p", binary=True)
image = Image.open(io.BytesIO(raw)).convert("RGB")
return image
def foreground(self):
value = self.run("shell", "dumpsys", "activity", "activities")
lines = [s for s in value.splitlines() if "topResumedActivity=" in s or "mResumedActivity:" in s or "mResumedActivity=" in s]
return bool(lines) and all("air.net.pixvi.myrzx" in s for s in lines)
def tap(self, x, y):
if not self.foreground():
raise RuntimeError("游戏不在前台,刷图已停止")
self.run("shell", "input", "tap", str(int(x)), str(int(y)))
@dataclass
class FarmConfig:
stage_id: str = "bd00"
stage_level: str = "1"
daily_limit: int = 3
keep_stamina: int = 0
timeout: int = 240
threshold: float = 0.96
templates: dict = field(default_factory=dict)
capture_profile: str = ""
class FarmBudget:
def __init__(self, path):
self.path = Path(path)
self.records = json.loads(self.path.read_text(encoding="utf-8")) if self.path.exists() else {}
def key(self, snapshot, config):
day = datetime.fromtimestamp(snapshot.now, timezone(timedelta(hours=8))).strftime("%Y-%m-%d")
return f"{snapshot.raw['master']['id']}:{config.stage_id}:{day}"
def used(self, snapshot, config):
return self.records.get(self.key(snapshot, config), 0)
def reserve(self, snapshot, config):
key = self.key(snapshot, config)
self.records[key] = self.records.get(key, 0) + 1
self.path.parent.mkdir(parents=True, exist_ok=True)
temporary = self.path.with_suffix(".tmp")
temporary.write_text(json.dumps(self.records), encoding="utf-8")
temporary.replace(self.path)
def check(self, snapshot, config, catalog):
if time.time() - snapshot.received_at > 30:
return False, "角色状态超过30秒未刷新"
if self.used(snapshot, config) >= config.daily_limit:
return False, "已达到本日设置的刷图上限"
stage = catalog.data["stage_info"].get(config.stage_id)
if not stage:
return False, "未找到此关卡的数据"
base = stage.get("cost", {})
cost = float(base.get("ti", 0)) + float(stage.get("level", {}).get(config.stage_level, {}).get("cost", 0))
if float(snapshot.raw["master"].get("ti", 0)) < cost + config.keep_stamina:
return False, "剩余体力不足或已达到保留体力"
counts = {str(i["typeId"]): int(i.get("num", 0)) for i in snapshot.raw["items"]}
for item in base.get("items", []):
if counts.get(str(item["typeId"]), 0) < int(item["num"]):
return False, "关卡入场券/每日可用次数已不足"
if float(snapshot.raw["master"].get("money", 0)) < float(base.get("money", 0)):
return False, "关卡金币消耗不足"
if float(base.get("ke", 0)):
return False, "此关卡需要氪金,未启用"
return True, f"可继续,今日已开始 {self.used(snapshot, config)} 轮"
def matches(image, template, folder, threshold):
width, height = template["screen"]
if template.get("strict_resolution") and image.size != (width, height):
return False
if abs(image.width / image.height - width / height) > 0.02:
return False
image = image.resize((width, height))
box = tuple(template["box"])
crop = image.crop(box).convert("RGB")
with Image.open(Path(folder) / template["file"]) as reference:
diff = ImageChops.difference(crop, reference.convert("RGB"))
similarity = 1 - sum(ImageStat.Stat(diff).mean) / (3 * 255)
return similarity >= threshold
class FarmRunner:
def __init__(self, adb, catalog, folder):
self.adb, self.catalog = adb, catalog
self.folder = Path(folder)
self.budget = FarmBudget(self.folder / "daily_runs.json")
self.config = FarmConfig()
self.state = "idle"
self.started = 0
self.last_tap = 0
self.running = False
self.completed = 0
def start(self):
if self.config.capture_profile:
self.config.templates = load_buttons(self.folder / self.config.capture_profile, self.folder,
self.config.stage_id, self.config.stage_level, self.adb.serial)
if not {"entry", "victory", "stage"}.issubset(self.config.templates):
raise ValueError("先截取关卡名称、进入按钮和胜利结算按钮")
if any(t.get("stage_id") != self.config.stage_id for t in self.config.templates.values()):
raise ValueError("标定不属于当前关卡,请为所选关卡重新标定按钮")
if any(str(t.get("stage_level", "1")) != self.config.stage_level for t in self.config.templates.values()):
raise ValueError("按钮配置属于其他难度,请加载对应页面配置")
self.state, self.running = "idle", True
def stop(self):
self.running = False
def tick(self, snapshot):
if not self.running:
return "已停止"
if not self.adb.foreground():
self.stop()
raise RuntimeError("游戏不在前台,刷图已停止")
templates = self.config.templates
devices = {t["device_serial"] for t in templates.values() if t.get("device_serial")}
if devices:
serial = self.adb.serial or self.adb.run("get-serialno").strip()
if devices != {serial}:
self.stop()
raise RuntimeError("当前手机与截图配置的设备不一致,已停止")
image = self.adb.screenshot()
if any(t.get("strict_resolution") and list(image.size) != t["screen"] for t in templates.values()):
self.stop()
raise RuntimeError("手机分辨率已变化,请补拍对应页面并重新生成配置")
visible = {name: matches(image, value, self.folder, self.config.threshold) for name, value in templates.items()}
now = time.monotonic()
if self.state != "idle" and now - self.started > self.config.timeout:
self.stop()
raise RuntimeError("战斗/结算等待超时,已停止;请检查手机画面")
if visible.get("defeat"):
self.stop()
raise RuntimeError("检测到战斗失败,已停止刷图")
if now - self.last_tap < 2:
return "等待画面更新"
button = None
if visible.get("entry"):
if self.state == "settling":
self.completed += 1
self.state = "idle"
return "结算完成,等待刷新体力和次数"
if self.state == "idle":
if not visible.get("stage"):
return "准备页关卡名称不匹配,未点击进入"
allowed, reason = self.budget.check(snapshot, self.config, self.catalog)
if not allowed:
self.stop()
return reason
# Count attempts before tapping, including interrupted/failed attempts.
self.budget.reserve(snapshot, self.config)
self.state, self.started, button = "battle", now, "entry"
elif self.state in ("battle", "settling"):
if visible.get("victory"):
self.state, button = "settling", "victory"
elif self.state == "settling" and visible.get("continue"):
button = "continue"
elif self.state == "battle":
button = next((name for name in ("countdown", "auto_off") if visible.get(name)), None)
if button and self.running:
template = templates[button]
x1, y1, x2, y2 = template["box"]
width, height = template["screen"]
tap_x, tap_y = template.get("tap", [(x1 + x2) / 2, (y1 + y2) / 2])
self.adb.tap(tap_x * image.width / width, tap_y * image.height / height)
self.last_tap = now
return f"点击 {button};完成 {self.completed} 轮"
return "等待匹配按钮;请勿切换到其他关卡"
+34 -18
View File
@@ -1,5 +1,6 @@
"""Conservative item gifting, using the original client's caps and cooldown."""
from .model import Action, seconds
from .cultivation import CultivationSelector
def item_reserve(item_type, ranch, quests):
@@ -7,15 +8,20 @@ def item_reserve(item_type, ranch, quests):
class GiftPlanner:
def __init__(self, catalog):
def __init__(self, catalog, cultivation=None):
self.catalog = catalog
self.cultivation = cultivation or CultivationSelector(catalog)
self.notes = []
def candidates(self, snapshot, policy):
if policy.gift_auto_representative:
return sorted(self.cultivation.select(snapshot).values(), key=lambda mon: self.cultivation.rank(mon), reverse=True)
monsters = snapshot.monsters
return [monsters[int(key)] for key, _ in sorted(policy.gift_targets.items(), key=lambda pair: pair[1])
if int(key) in monsters and monsters[int(key)].get("process") == 3]
def target(self, snapshot, policy):
for key, _ in sorted(policy.gift_targets.items(), key=lambda pair: pair[1]):
mon = snapshot.monsters.get(int(key))
if not mon or mon.get("process") != 3:
continue
for mon in self.candidates(snapshot, policy):
limit = self.catalog.max_feel(mon)
if int(mon.get("feel") or 0) < limit:
return mon, limit
@@ -28,16 +34,6 @@ class GiftPlanner:
if not any(rule.get("enabled") for rule in policy.gift_items.values()):
self.notes.append("自动赠礼:请先在“背包”勾选允许使用的物品")
return []
target, limit = self.target(snapshot, policy)
if not target:
self.notes.append("自动赠礼:未选择目标,或目标已达到当前好感上限")
return []
cooldown = int(self.catalog.data["game_setting"].get("monGiftTime", 7200))
elapsed = snapshot.now - seconds(target.get("giftTime"))
if elapsed < cooldown:
self.notes.append(f"自动赠礼:{self.catalog.monster_label(target)} 还需等待 {int(cooldown - elapsed)} 秒")
return []
likes = self.catalog.monster(target.get("typeId")).get("like") or {}
totals, blocked = {}, set()
for item in snapshot.raw["items"]:
key = str(item.get("typeId"))
@@ -54,13 +50,33 @@ 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 and (not policy.gift_liked_only or int(likes.get(key, 0)) > 0):
if available:
stocks[key] = available
if not stocks:
self.notes.append("自动赠礼:背包中没有符合开关、保留数量和偏好规则的物品")
self.notes.append("自动赠礼:背包中没有符合开关和保留数量的物品")
return []
key = max(stocks, key=lambda k: (int(likes.get(k, 0)), stocks[k], -int(k)))
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
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
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)})]
self.notes.append("自动赠礼:培养代表已达好感上限、处于冷却或缺少允许的礼物" if policy.gift_auto_representative
else "自动赠礼:未选择目标、目标已达当前好感上限或没有符合偏好的礼物")
return []
+421 -675
View File
File diff suppressed because it is too large Load Diff
+9 -24
View File
@@ -1,9 +1,9 @@
"""Native, incremental inventory and combined ranch/monster views."""
import copy
from dataclasses import asdict
from PySide6 import QtCore as C, QtWidgets as W
from .native_widgets import IntegerInput, RowBatch
from .table_widgets import CenteredCheckBox, bind_controls, set_value, table_item
ITEM_TYPES = [(0, "全部物品"), (6, "魔物蛋"), (1, "可使用"), (2, "消耗品"), (3, "材料"), (4, "其他"), (5, "装备")]
@@ -57,11 +57,13 @@ class InventoryTable(W.QTableWidget):
values = [", ".join(item["inventoryIds"]), self.catalog.item_name(key), dict(ITEM_TYPES)[type_id], info.get("quality", info.get("star", "")),
item.get("num", 0), info.get("sellMoney", ""), "", ""]
for column, value in enumerate(values):
cell = self.item(index, column) or W.QTableWidgetItem()
cell.setData(C.Qt.ItemDataRole.DisplayRole, value)
cell = self.item(index, column)
if cell is None:
cell = table_item(value, column)
self.setItem(index, column, cell)
set_value(cell, column, value)
if column == 0:
cell.setData(C.Qt.ItemDataRole.UserRole, key)
self.setItem(index, column, cell)
eligible = type_id not in (5, 6) and bool(info.get("sellable"))
check, reserve = self.cellWidget(index, 6), self.cellWidget(index, 7)
if check and check.property("item_type") == key:
@@ -70,8 +72,9 @@ class InventoryTable(W.QTableWidget):
reserve.setValue(int(rule.get("reserve", 0)))
check.setEnabled(eligible)
reserve.setEnabled(eligible)
bind_controls(self, index, {6: check, 7: reserve})
return
check, reserve = W.QCheckBox(), IntegerInput()
check, reserve = CenteredCheckBox(), IntegerInput()
check.setProperty("item_type", key)
check.setEnabled(eligible)
check.setChecked(bool(rule.get("enabled")))
@@ -86,26 +89,8 @@ class InventoryTable(W.QTableWidget):
reserve.valueChanged.connect(commit)
self.setCellWidget(index, 6, check)
self.setCellWidget(index, 7, reserve)
bind_controls(self, index, {6: check, 7: reserve})
def finish():
self.setSortingEnabled(True)
self.render_signature = copy.deepcopy(signature)
self.row_batch.start(enumerate(rows), apply, finish)
class RanchView(W.QSplitter):
def __init__(self, rooms, monsters):
super().__init__(C.Qt.Orientation.Vertical)
self.rooms, self.monsters = rooms, monsters
self.grouped = True
self.room_id = 0
self.setChildrenCollapsible(False)
self.addWidget(rooms)
self.addWidget(monsters)
self.setStretchFactor(0, 0)
self.setStretchFactor(1, 1)
self.setSizes([100, 440])
def set_view(self, grouped, room_id=0):
self.grouped, self.room_id = grouped, room_id
self.rooms.setVisible(grouped)
self.setSizes([100, 440] if grouped else [0, 540])
+71
View File
@@ -0,0 +1,71 @@
"""Client-equivalent player level and natural stamina settlement."""
import time
from .model import seconds
class MasterSync:
def __init__(self, catalog):
self.catalog = catalog
self.attempts = {}
self.level = 0
self.stamina = None
def apply(self, snapshot):
master = dict(snapshot.raw["master"])
snapshot.raw["master"] = master
# A confirmed level cannot regress within this role's session.
master["level"] = max(int(master.get("level") or 1), self.level)
if self.stamina:
before, after, expires = self.stamina
pair = (master.get("ti"), master.get("timeTi"))
if pair == before and time.monotonic() < expires:
master.update(ti=after[0], timeTi=after[1])
else:
self.stamina = None
def pending(self, snapshot):
if snapshot is None:
return []
master = snapshot.raw["master"]
settings = self.catalog.data.get("game_setting", {})
level = int(master.get("level") or 1)
threshold = self.catalog.data.get("farm_level", {}).get(str(level + 1))
paths = []
if (level < int(settings.get("masterMaxLevel", 70)) and threshold is not None
and float(master.get("exp") or 0) >= float(threshold)):
paths.append("masterService/masterLevelUpdate")
timestamp = seconds(master.get("timeTi"))
cooldown = float(settings.get("tiCD") or 150)
if timestamp > 0 and snapshot.now - timestamp >= cooldown:
paths.append("masterService/masterCheckTiAdd")
now = time.monotonic()
return [path for path in paths if now >= self.attempts.get(path, 0)]
def settle(self, client, snapshot):
master = snapshot.raw["master"]
updated = []
for path in self.pending(snapshot):
# Includes failures and unchanged replies; never spin on a stale value.
self.attempts[path] = time.monotonic() + 30
response = client.call(path, {})
if path.endswith("masterLevelUpdate"):
value = response.get("level")
if isinstance(value, bool) or not isinstance(value, (int, float)) or int(value) != value or value < int(master["level"]):
raise ValueError("升级响应缺少有效的角色等级")
self.level = int(value)
master["level"] = self.level
updated.append("等级")
else:
ti, timestamp = response.get("ti"), response.get("timeTi")
if (isinstance(ti, bool) or not isinstance(ti, (int, float)) or int(ti) != ti or ti < 0
or not isinstance(timestamp, (int, float)) or isinstance(timestamp, bool) or timestamp <= 0):
raise ValueError("体力恢复响应缺少有效的 ti / timeTi")
before = (master.get("ti"), master.get("timeTi"))
after = (int(ti), timestamp)
# Apply only over the exact pre-settlement pair, for a bounded
# period. A new cost/reward from the server always takes priority.
self.stamina = (before, after, time.monotonic() + 60)
master.update(ti=after[0], timeTi=after[1])
updated.append("体力")
return updated
+26 -2
View File
@@ -5,6 +5,7 @@ import json
import math
from pathlib import Path
import time
from .cultivation import CultivationSelector, growth_score
WIKI = "https://wiki.biligame.com/myrzx/魔物收益表"
@@ -299,6 +300,8 @@ class Policy:
gift_targets: dict[str, int] = field(default_factory=dict)
gift_items: dict[str, dict] = field(default_factory=dict)
gift_liked_only: bool = True
gift_auto_representative: bool = False
keep_better_quality: bool = False
def __post_init__(self):
self.egg_rules = {str(int(key)): asdict(EggRule(**rule)) for key, rule in self.egg_rules.items()}
@@ -317,8 +320,9 @@ class Action:
class Planner:
def __init__(self, catalog):
def __init__(self, catalog, cultivation=None):
self.catalog = catalog
self.cultivation = cultivation or CultivationSelector(catalog)
self.managed = set()
self.notes = []
self.restocking = set()
@@ -341,6 +345,20 @@ class Planner:
if condition:
return reason
quality = math.ceil(sum(qualities) / 4)
if policy.keep_better_quality or policy.gift_auto_representative:
representative = self.cultivation.select(snapshot).get(str(mon.get("typeId")))
if representative and int(representative["id"]) == int(mon["id"]):
return "同种魔物的唯一培养代表(等级、好感、资质优先)"
if policy.keep_better_quality:
if representative is None:
return "牧场尚无同种魔物,保留首次获得的魔物"
baseline, candidate = growth_score(self.catalog, representative), growth_score(self.catalog, mon)
if baseline is None:
return "同种培养代表的资质尚未同步,暂时保留"
if candidate is not None and candidate > baseline + 1e-8:
return f"综合成长资质高于同种培养代表 #{representative['id']}({candidate:.1%} > {baseline:.1%})"
if policy.protect_quality == 6:
return "攻/防/生命/敏捷四项资质全S(4S)" if all(q == 4 for q in qualities) else ""
if quality >= policy.protect_quality:
return f"综合资质{'CBAS'[quality - 1]}达到保留资质{'CBAS'[policy.protect_quality - 1]}"
return ""
@@ -530,6 +548,12 @@ class Planner:
self.notes.append(f"{name} 已保留:{reason}")
if actions:
return self.batch_actions(actions, snapshot, policy)
return self.hatch_actions(snapshot, policy) or self.purchase(snapshot, policy, daily_left)
def hatch_actions(self, snapshot, policy):
if not policy.enabled or not policy.fill:
return []
actions = []
vip_info = snapshot.raw.get("activityHistory", {}).get("vipInfo") or {}
vip = seconds(vip_info.get("vipTime")) > snapshot.now
empty = [s for s in snapshot.raw["stacks"] if policy.fill and int(s.get("monsterId") or 0) <= 0 and (int(s.get("position", -1)) != 3 or vip)]
@@ -554,7 +578,7 @@ class Planner:
self.notes.append("有空坑,当前没有符合已勾选规则和保留数量的蛋" if policy.manual_eggs else "有空坑,当前没有符合星级、收益和保留数量设置的蛋")
if not actions and not self.notes:
self.notes.append("等待孵化 / 成长,成熟后按保护条件处理")
return actions or self.purchase(snapshot, policy, daily_left)
return actions
def batch_actions(self, actions, snapshot, policy):
monsters = snapshot.monsters
+131 -1
View File
@@ -3,6 +3,111 @@ from PySide6 import QtCore as C, QtGui as G, QtWidgets as W
import time
class FocusWheelMixin:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# StrongFocus permits click/keyboard focus, but never wheel focus.
self.setFocusPolicy(C.Qt.FocusPolicy.StrongFocus)
def wheelEvent(self, event):
if not self.hasFocus():
event.ignore()
return
super().wheelEvent(event)
class SpinBox(FocusWheelMixin, W.QSpinBox):
pass
class DoubleSpinBox(FocusWheelMixin, W.QDoubleSpinBox):
pass
class ComboBox(W.QComboBox):
"""Size popups for their text, independently of narrow table columns."""
def __init__(self, parent=None):
self._text_width = None
self._text_alignment = None
super().__init__(parent)
self.setSizeAdjustPolicy(W.QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon)
self.setMinimumContentsLength(6)
self.setMaxVisibleItems(12)
view = W.QListView(self)
view.setTextElideMode(C.Qt.TextElideMode.ElideNone)
view.setHorizontalScrollBarPolicy(C.Qt.ScrollBarPolicy.ScrollBarAsNeeded)
view.setHorizontalScrollMode(W.QAbstractItemView.ScrollMode.ScrollPerPixel)
self.setView(view)
for signal in (self.model().dataChanged, self.model().rowsInserted, self.model().rowsRemoved, self.model().modelReset):
signal.connect(self.invalidate_width)
def invalidate_width(self, *args):
self._text_width = None
self.updateGeometry()
def text_width(self):
if self._text_width is None:
self._text_width = max((self.fontMetrics().horizontalAdvance(self.itemText(i)) for i in range(self.count())), default=0)
return self._text_width
def sizeHint(self):
hint = super().sizeHint()
hint.setWidth(max(120, hint.width(), min(360, self.text_width() + 48)))
return hint
def minimumSizeHint(self):
hint = super().minimumSizeHint()
hint.setWidth(max(120, hint.width(), min(260, self.text_width() + 48)))
return hint
def changeEvent(self, event):
if event.type() in (C.QEvent.Type.FontChange, C.QEvent.Type.StyleChange):
self.invalidate_width()
super().changeEvent(event)
def showPopup(self):
view = self.view()
screen = self.screen().availableGeometry()
scrollbar = view.verticalScrollBar().sizeHint().width()
content = max(self.text_width() + 16, view.sizeHintForColumn(0))
width = min(screen.width(), max(self.width(), content + scrollbar + 2 * view.frameWidth() + 8))
popup = view.window()
frame = popup.frameWidth() if isinstance(popup, W.QFrame) else 0
view.setMinimumWidth(max(0, width - 2 * frame))
super().showPopup()
# QComboBox resets this policy while opening its popup.
view.setHorizontalScrollBarPolicy(C.Qt.ScrollBarPolicy.ScrollBarAsNeeded)
popup.resize(width, popup.height())
view.doItemsLayout()
if view.horizontalScrollBar().maximum() > 0:
popup.resize(width, min(screen.height(), popup.height() + view.horizontalScrollBar().sizeHint().height()))
popup.move(min(max(popup.x(), screen.left()), screen.right() - popup.width() + 1),
min(max(popup.y(), screen.top()), screen.bottom() - popup.height() + 1))
def event(self, event):
if event.type() == C.QEvent.Type.ToolTip and self.currentText():
text = self.currentText()
if self.toolTip() and self.toolTip() != text:
text += "\n" + self.toolTip()
W.QToolTip.showText(event.globalPos(), text, self)
return True
return super().event(event)
def setTextAlignment(self, alignment):
self._text_alignment = alignment
self.update()
def paintEvent(self, event):
if self._text_alignment is None:
return super().paintEvent(event)
painter = W.QStylePainter(self)
option = W.QStyleOptionComboBox()
self.initStyleOption(option)
option.textAlignment = self._text_alignment
painter.drawComplexControl(W.QStyle.ComplexControl.CC_ComboBox, option)
painter.drawControl(W.QStyle.ControlElement.CE_ComboBoxLabel, option)
class RowBatch(C.QObject):
"""Create Qt rows in short event-loop slices, keeping input responsive."""
def __init__(self, parent):
@@ -45,6 +150,8 @@ class IntegerInput(W.QLineEdit):
def __init__(self):
super().__init__()
self._value, self._minimum, self._maximum = 0, 0, 2147483647
self._wheel_delta = 0
self.setFocusPolicy(C.Qt.FocusPolicy.StrongFocus)
self.setValidator(G.QIntValidator(self._minimum, self._maximum, self))
self.setText("0")
self.setMinimumWidth(76)
@@ -55,7 +162,13 @@ class IntegerInput(W.QLineEdit):
return self._value
def setValue(self, value):
self.setText(str(min(self._maximum, max(self._minimum, int(value)))))
value = min(self._maximum, max(self._minimum, int(value)))
changed = value != self._value
# Signal blockers must not prevent updates to the stored numeric value.
self._value = value
self.setText(str(value))
if changed:
self.valueChanged.emit(value)
def setRange(self, minimum, maximum):
self._minimum, self._maximum = int(minimum), int(maximum)
@@ -75,6 +188,23 @@ class IntegerInput(W.QLineEdit):
def finish_number(self):
self.setValue(self._value)
def wheelEvent(self, event):
if not self.hasFocus() or not event.angleDelta().y():
event.ignore()
return
self._wheel_delta += event.angleDelta().y()
steps = int(self._wheel_delta / 120)
self._wheel_delta -= steps * 120
if steps:
if event.modifiers() & C.Qt.KeyboardModifier.ControlModifier:
steps *= 10
self.setValue(self.value() + steps)
event.accept()
def focusOutEvent(self, event):
self._wheel_delta = 0
super().focusOutEvent(event)
class NativeScrollStyle(W.QProxyStyle):
def pixelMetric(self, metric, option=None, widget=None):
+90 -2
View File
@@ -1,9 +1,34 @@
"""Portable rule sets; credentials, sessions and local paths never enter files."""
import copy
import math
from dataclasses import asdict
from .model import Policy
from .daily import DailyPolicy
from .quests import QuestPolicy
from .sweeping import SweepPolicy
FORMAT = "ranch-helper-policies"
VERSION = 1
CONFIG_VERSION = 2
def checked_policy(cls, data):
if not isinstance(data, dict):
raise ValueError("策略配置必须是对象")
for key, default in asdict(cls()).items():
if key not in data:
continue
value = data[key]
if cls.__annotations__.get(key) in (float, "float"):
valid = type(value) in (int, float) and math.isfinite(value)
else:
valid = type(value) is type(default)
if not valid:
raise ValueError("策略字段类型错误:" + key)
try:
return cls(**data)
except (AttributeError, TypeError, KeyError) as error:
raise ValueError("策略字段格式错误") from error
def portable_policy(policy, snapshot=None):
@@ -11,6 +36,9 @@ def portable_policy(policy, snapshot=None):
value["enabled"] = False
for field in ("buy", "collect", "dispatch", "feed", "fill", "gift_enabled"):
value[field] = False
if value["feed_target"] and not value["feed_targets"]:
value["feed_targets"] = {str(value["feed_target"]): 1}
value["feed_target"] = value["room_id"] = 0
targets = {}
for kind, field in (("feed", "feed_targets"), ("gift", "gift_targets")):
targets[kind] = []
@@ -24,12 +52,18 @@ def portable_policy(policy, snapshot=None):
def import_policy(value, snapshot=None):
if not isinstance(value, dict) or value.get("format") != FORMAT or value.get("schema") != VERSION or not isinstance(value.get("policy"), dict):
raise ValueError("不是受支持的辅助策略文件")
policy = Policy(**value["policy"])
policy = checked_policy(Policy, value["policy"])
policy.feed_target = policy.room_id = 0
if snapshot:
used = {"feed": set(), "gift": set()}
for kind, field in (("feed", "feed_targets"), ("gift", "gift_targets")):
result = {}
for rule in value.get("targetSpecies", {}).get(kind, []):
targets = value.get("targetSpecies", {})
if not isinstance(targets, dict) or not isinstance(targets.get(kind, []), list):
raise ValueError("培养目标配置格式错误")
for rule in targets.get(kind, []):
if not isinstance(rule, dict) or not 1 <= int(rule.get("priority", 0)) <= 999:
raise ValueError("培养目标优先级格式错误")
key = str(rule.get("typeId", ""))
for mon in sorted(snapshot.raw["monsters"], key=lambda m: int(m["id"])):
if str(mon.get("typeId")) == key and mon.get("process") == 3 and int(mon["id"]) not in used[kind]:
@@ -40,3 +74,57 @@ def import_policy(value, snapshot=None):
else:
policy.feed_targets, policy.gift_targets = {}, {}
return policy
def portable_config(config, snapshot=None):
"""One portable file for all strategies, independent of session/UI state."""
policy = Policy(**config.get("policy", {}))
value = portable_policy(policy, snapshot)
value["schema"] = CONFIG_VERSION
# These are configuration choices. The GUI execution switch is deliberately
# outside the portable document and stays stopped on import.
for field in ("enabled", "buy", "collect", "dispatch", "feed", "fill", "gift_enabled"):
value["policy"][field] = getattr(policy, field)
for key, cls in (("quest_policy", QuestPolicy), ("daily_policy", DailyPolicy), ("sweep_policy", SweepPolicy)):
value[key] = asdict(cls(**config.get(key, {})))
value["interval"] = config.get("interval", 30)
value["overrides"] = copy.deepcopy(config.get("overrides", {}))
value["yield_stars"] = list(config.get("yield_stars", [1, 2, 3, 4, 5]))
return value
def import_config(value, snapshot=None):
if not isinstance(value, dict) or value.get("format") != FORMAT:
raise ValueError("不是受支持的辅助策略文件")
if value.get("schema") == VERSION:
return {"policy": asdict(import_policy(value, snapshot))}
if value.get("schema") != CONFIG_VERSION:
raise ValueError("不支持此策略文件版本")
config = {"policy": asdict(import_policy(value | {"schema": VERSION}, snapshot))}
for key, cls in (("quest_policy", QuestPolicy), ("daily_policy", DailyPolicy), ("sweep_policy", SweepPolicy)):
if not isinstance(value.get(key), dict):
raise ValueError("策略文件缺少 " + key)
config[key] = asdict(checked_policy(cls, value[key]))
interval = value.get("interval", 30)
if interval not in (30, 60, 120, 300):
raise ValueError("刷新间隔须为30、60、120或300秒")
overrides, stars = value.get("overrides", {}), value.get("yield_stars", [1, 2, 3, 4, 5])
if not isinstance(overrides, dict) or not isinstance(stars, list) or any(type(s) is not int or s not in range(1, 6) for s in stars):
raise ValueError("收益资料配置格式错误")
for key, row in overrides.items():
if (not str(key).isdigit() or not isinstance(row, dict)
or any(field not in ("sell_money", "sell_exp", "time_total") or type(number) not in (int, float)
or not math.isfinite(number) or number < 0 for field, number in row.items())):
raise ValueError("收益资料配置格式错误")
for rule in config["sweep_policy"]["rules"].values():
if (not isinstance(rule, dict) or str(rule.get("level", "3")) not in ("1", "2", "3")
or type(rule.get("limit", 3)) is not int or not 0 <= rule.get("limit", 3) <= 999
or type(rule.get("enabled", False)) is not bool):
raise ValueError("扫荡规则格式错误")
if any(not isinstance(key, str) for key in config["daily_policy"]["selected"]):
raise ValueError("每日事务规则格式错误")
if any(not str(key).isdigit() or type(count) is not int or count < 0
for key, count in config["quest_policy"]["item_reserves"].items()):
raise ValueError("委托保留物品规则格式错误")
config.update(interval=interval, overrides=copy.deepcopy(overrides), yield_stars=list(stars))
return config
+6 -2
View File
@@ -25,6 +25,9 @@ class Views:
monsters: list
map_source: str
maps: list
stage_cache: object = None
statistics_store: object = None
drop_statistics: dict = None
@dataclass
@@ -35,6 +38,7 @@ class Presented:
worker_ms: float = 0
def prepare_views(catalog, snapshot, managed):
def prepare_views(catalog, snapshot, managed, stage_cache=None, statistics=None):
return Views(snapshot, repr(snapshot.raw["monsters"]), set(managed), monster_rows(catalog, snapshot, managed),
map_source(snapshot), stages(catalog, snapshot))
str(snapshot.raw["master"]["id"]), stage_cache.get(snapshot) if stage_cache else stages(catalog, snapshot), stage_cache,
statistics, statistics.snapshot(snapshot.raw["master"]["id"]) if statistics else None)
+151
View File
@@ -0,0 +1,151 @@
"""Incremental monster tree with ranch headers or a flat list."""
import copy
from collections import Counter
from PySide6 import QtCore as C, QtWidgets as W
from .native_widgets import IntegerInput, RowBatch
from .table_widgets import CenteredCheckBox, TreeItem, bind_controls, set_value
class RanchView(W.QTreeWidget):
feed_changed = C.Signal(str, bool, int)
gift_changed = C.Signal(str, bool, int)
monster_activated = C.Signal(int)
def __init__(self, catalog):
super().__init__()
self.catalog = catalog
self.setHeaderLabels(["牧场 / 魔物ID", "名称", "星", "等级 / 当前上限", "资质 攻/防/血/敏", "位置", "锁定", "管理范围",
"喂养目标", "喂养优先级", "突破等级", "参考攻击", "参考防御", "参考生命", "参考敏捷", "好感 / 当前上限", "喜欢的物品", "赠礼", "赠礼优先级"])
self.header().setSectionResizeMode(W.QHeaderView.ResizeMode.Interactive)
for column, width in enumerate((260, 140, 45, 120, 150, 140, 80, 130, 90, 110, 85, 90, 90, 90, 90, 90, 220, 65, 110)):
self.setColumnWidth(column, width)
self.setSelectionMode(W.QAbstractItemView.SelectionMode.ExtendedSelection)
self.setSelectionBehavior(W.QAbstractItemView.SelectionBehavior.SelectRows)
self.setEditTriggers(W.QAbstractItemView.EditTrigger.NoEditTriggers)
self.setUniformRowHeights(True)
self.setAllColumnsShowFocus(True)
self.grouped, self.room_id = True, 0
self.monster_items, self.group_items, self.expansion = {}, {}, {}
self.render_signature = None
self.row_batch = RowBatch(self)
self.itemDoubleClicked.connect(self.activate_monster)
def activate_monster(self, item, column):
mid = item.data(0, C.Qt.ItemDataRole.UserRole)
if mid is not None:
self.monster_activated.emit(int(mid))
def selected_monster_ids(self):
return [int(item.data(0, C.Qt.ItemDataRole.UserRole)) for item in self.selectedItems()
if item.data(0, C.Qt.ItemDataRole.UserRole) is not None]
def set_view(self, grouped, room_id=0):
self.grouped, self.room_id = grouped, room_id if grouped else 0
@staticmethod
def group_key(mon):
if mon.get("process") == 2:
return "incubator"
return f"room:{int(mon.get('roomId') or 0)}"
def set_data(self, snapshot, rows, feed_targets, gift_targets):
monsters = snapshot.raw["monsters"]
entries = [(mon, values) for mon, values in zip(monsters, rows)
if not self.room_id or mon.get("process") == 3 and int(mon.get("roomId") or 0) == self.room_id]
signature = (entries, snapshot.raw["rooms"], feed_targets, gift_targets, self.grouped, self.room_id)
if self.render_signature == signature:
return
self.row_batch.stop()
self.render_signature = None
self.setSortingEnabled(False)
selected = set(self.selected_monster_ids())
self.expansion.update({key: item.isExpanded() for key, item in self.group_items.items()})
counts = Counter(self.group_key(mon) for mon, _ in entries)
groups = {}
if self.grouped:
for room in snapshot.raw["rooms"]:
rid = int(room["id"])
if self.room_id and rid != self.room_id:
continue
key = f"room:{rid}"
info = self.catalog.data["room_info"].get(str(room.get("typeId")), {})
capacity = info.get("maxNum")
label = f"{room.get('name') or info.get('name') or '牧场'} #{rid} | 魔物 {counts[key]}"
if capacity is not None:
label += f" / {capacity} | 空位 {max(0, int(capacity) - counts[key])}"
groups[key] = label
for key, count in counts.items():
if key not in groups:
label = "培育室" if key == "incubator" else "未归属牧场" if key == "room:0" else "牧场 #" + key.split(":")[1]
groups[key] = f"{label} | 魔物 {count}"
wanted = {int(mon["id"]): self.group_key(mon) if self.grouped else None for mon, _ in entries}
for mid, item in list(self.monster_items.items()):
current_group = item.parent().data(0, C.Qt.ItemDataRole.UserRole + 1) if item.parent() is not None else None
if mid not in wanted or current_group != wanted[mid]:
self.remove_item(item)
del self.monster_items[mid]
for key, item in list(self.group_items.items()):
if key not in groups:
self.remove_item(item)
del self.group_items[key]
for key, label in groups.items():
item = self.group_items.get(key)
if item is None:
item = TreeItem(self, [label])
item.setData(0, C.Qt.ItemDataRole.UserRole + 1, key)
item.setFirstColumnSpanned(True)
item.setSizeHint(0, C.QSize(100, 26))
item.setFlags(item.flags() & ~C.Qt.ItemFlag.ItemIsSelectable)
item.setExpanded(self.expansion.get(key, True))
self.group_items[key] = item
item.setText(0, label)
self.setRootIsDecorated(self.grouped)
def apply(entry):
mon, values = entry
mid = int(mon["id"])
item = self.monster_items.get(mid)
if item is None:
parent = self.group_items.get(wanted[mid])
item = TreeItem(parent if parent is not None else self)
item.setData(0, C.Qt.ItemDataRole.UserRole, mid)
self.monster_items[mid] = item
for check_column, priority_column, signal in ((8, 9, self.feed_changed), (17, 18, self.gift_changed)):
check, priority = CenteredCheckBox(), IntegerInput()
priority.setRange(1, 999)
def changed(*args, check=check, priority=priority, signal=signal, mid=mid):
signal.emit(str(mid), check.isChecked(), priority.value())
check.toggled.connect(changed)
priority.valueChanged.connect(changed)
self.setItemWidget(item, check_column, check)
self.setItemWidget(item, priority_column, priority)
item.setSizeHint(0, C.QSize(100, 26))
item.setSelected(mid in selected)
for column, value in enumerate(values):
if item.data(column, C.Qt.ItemDataRole.DisplayRole) != value:
set_value(item, column, value)
item.setToolTip(16, str(values[16]))
for check_column, priority_column, targets in ((8, 9, feed_targets), (17, 18, gift_targets)):
check, priority = self.itemWidget(item, check_column), self.itemWidget(item, priority_column)
blockers = [C.QSignalBlocker(check), C.QSignalBlocker(priority)]
check.setChecked(str(mid) in targets)
check.setEnabled(mon.get("process") == 3)
priority.setEnabled(mon.get("process") == 3)
if not priority.hasFocus():
priority.setValue(targets.get(str(mid), 100))
bind_controls(self, item, {column: self.itemWidget(item, column) for column in (8, 9, 17, 18)})
def finish():
self.render_signature = copy.deepcopy(signature)
self.setSortingEnabled(True)
self.row_batch.start(entries, apply, finish)
def remove_item(self, item):
parent = item.parent()
if parent is None:
self.takeTopLevelItem(self.indexOfTopLevelItem(item))
else:
parent.takeChild(parent.indexOfChild(item))
-1
View File
@@ -1,5 +1,4 @@
PySide6>=6.8,<7
requests>=2.32,<3
cryptography>=43
Pillow>=11
openpyxl>=3.1,<4
+42
View File
@@ -0,0 +1,42 @@
"""Per-role map list, captured once and replaced only on explicit refresh."""
from dataclasses import asdict
import json
from pathlib import Path
from .maps import Stage, stages
class StageCache:
def __init__(self, catalog, path=None):
self.catalog = catalog
self.path = Path(path) if path else None
self.owner = None
self.rows = None
self.saved_at = 0
self.revision = 0
def get(self, snapshot, *, refresh=False):
owner = str(snapshot.raw["master"]["id"])
if not refresh and self.rows is not None and self.owner == owner:
return self.rows
if not refresh and self.path and self.path.exists():
try:
value = json.loads(self.path.read_text(encoding="utf-8"))
if value.get("schema") == 1 and value.get("gameVersion") == "1.9.68" and value.get("owner") == owner:
self.rows = [Stage(**row) for row in value["stages"]]
self.owner, self.saved_at = owner, float(value["savedAt"])
self.revision += 1
return self.rows
except (OSError, ValueError, TypeError, KeyError, AttributeError):
pass
rows = stages(self.catalog, snapshot)
saved_at = snapshot.now
if self.path:
self.path.parent.mkdir(parents=True, exist_ok=True)
temporary = self.path.with_suffix(".tmp")
temporary.write_text(json.dumps({"schema": 1, "gameVersion": "1.9.68", "owner": owner,
"savedAt": saved_at, "stages": [asdict(row) for row in rows]}, ensure_ascii=False), encoding="utf-8")
temporary.replace(self.path)
self.rows, self.owner, self.saved_at = rows, owner, saved_at
self.revision += 1
return self.rows
+242
View File
@@ -0,0 +1,242 @@
"""Local single-stage drop analysis using native Qt tables and charts."""
from PySide6 import QtCore as C, QtGui as G, QtWidgets as W
from PySide6.QtCharts import QChart, QChartView, QHorizontalBarSeries, QBarSet, QBarCategoryAxis, QValueAxis
from .drop_statistics import analyze
from .native_widgets import ComboBox, RowBatch
from .table_widgets import TreeItem, table_item, SORT_ROLE
class StatisticsPage(W.QWidget):
refresh_requested = C.Signal()
def __init__(self, catalog):
super().__init__()
self.catalog = catalog
self.data = {"owner": "", "totals": {}, "drops": {}}
self.current_key = None
self.static_source = None
self.building = False
self.stage_items, self.level_items = {}, {}
self.row_batch = RowBatch(self)
layout = W.QVBoxLayout(self)
tools = W.QHBoxLayout()
self.search = W.QLineEdit()
self.search.setPlaceholderText("搜索关卡编号或名称")
self.source = ComboBox()
for label, value in (("普通扫荡", "sweep"), ("奖励事件", "event"), ("合计", "all")):
self.source.addItem(label, value)
self.chart_metric = ComboBox()
self.chart_metric.addItem("实测掉落率", "rate")
self.chart_metric.addItem("每点体力数量", "per_stamina")
refresh = W.QPushButton("刷新本地统计")
refresh.clicked.connect(self.refresh_requested)
tools.addWidget(self.search, 1)
tools.addWidget(W.QLabel("统计范围"))
tools.addWidget(self.source)
tools.addWidget(self.chart_metric)
tools.addWidget(refresh)
layout.addLayout(tools)
self.summary = W.QLabel("选择关卡和难度,查看当前账号的本地掉落统计。")
self.summary.setWordWrap(True)
layout.addWidget(self.summary)
self.splitter = W.QSplitter(C.Qt.Orientation.Horizontal)
self.tree = W.QTreeWidget()
self.tree.setHeaderLabels(["关卡 / 难度", "扫荡", "事件"])
self.tree.setUniformRowHeights(True)
self.tree.setSelectionMode(W.QAbstractItemView.SelectionMode.SingleSelection)
self.tree.setMinimumWidth(250)
self.tree.setColumnWidth(0, 180)
self.tree.setColumnWidth(1, 55)
self.tree.setColumnWidth(2, 55)
self.splitter.addWidget(self.tree)
right = W.QWidget()
right_layout = W.QVBoxLayout(right)
self.chart_scroll = W.QScrollArea()
self.chart_scroll.setWidgetResizable(True)
self.chart_scroll.setFrameShape(W.QFrame.Shape.NoFrame)
self.chart_view = QChartView()
self.chart_view.setRenderHint(G.QPainter.RenderHint.Antialiasing)
self.chart_scroll.setWidget(self.chart_view)
self.chart_scroll.setMinimumHeight(150)
right_layout.addWidget(self.chart_scroll, 1)
self.table = W.QTableWidget(0, 10)
self.table.setHorizontalHeaderLabels(["掉落物", "类别", "出现次数", "总数量", "样本数", "实测掉落率", "平均数量/次", "每点体力数量", "95%区间", "静态配置"])
self.table.setEditTriggers(W.QAbstractItemView.EditTrigger.NoEditTriggers)
self.table.setSelectionBehavior(W.QAbstractItemView.SelectionBehavior.SelectRows)
self.table.horizontalHeader().setSectionResizeMode(W.QHeaderView.ResizeMode.ResizeToContents)
self.table.horizontalHeader().setStretchLastSection(True)
self.table.verticalHeader().setDefaultSectionSize(22)
right_layout.addWidget(self.table, 1)
self.splitter.addWidget(right)
self.splitter.setSizes([320, 740])
self.splitter.setStretchFactor(1, 1)
layout.addWidget(self.splitter, 1)
note = W.QLabel("实测掉落率 = 出现次数 ÷ 已确认样本数;同次多件只记一次出现。每点体力数量 = 已知消耗样本的物品数量 ÷ 实际扣除体力,不扣减奖励返还的体力。\n不同难度、扫荡和事件分别统计;未知消耗样本不参与体力效率计算,消耗为0时不计算比值。无样本显示“—”;95%区间反映样本不确定性,实测结果不是官方掉率。")
note.setWordWrap(True)
layout.addWidget(note)
self.tree.currentItemChanged.connect(self.selection_changed)
self.source.currentIndexChanged.connect(self.render_detail)
self.chart_metric.currentIndexChanged.connect(self.render_detail)
self.search.textChanged.connect(self.filter_tree)
self.render_detail()
def set_data(self, catalog, data):
if self.data is data and self.catalog is catalog and self.static_source is catalog.data.get("stage_info"):
if self.building and not self.row_batch.running:
self.build_tree()
return
changed_owner = self.data.get("owner") != data.get("owner")
self.catalog, self.data = catalog, data
if changed_owner:
self.current_key = None
self.tree.setCurrentItem(None)
if self.current_key and self.current_key[0] not in catalog.data.get("stage_info", {}):
self.current_key = None
if self.static_source is not catalog.data.get("stage_info") or self.building and not self.row_batch.running:
self.build_tree()
else:
self.update_counts()
self.render_detail()
def count(self, stage, level, kind):
return self.data.get("totals", {}).get(f"{stage}:{level}:{kind}", {}).get("n", 0)
def build_tree(self):
self.static_source = self.catalog.data.get("stage_info")
self.row_batch.stop()
self.building = True
blocker = C.QSignalBlocker(self.tree)
self.tree.clear()
del blocker
self.stage_items, self.level_items = {}, {}
cities = {}
rows = sorted(self.catalog.data.get("stage_info", {}).items(), key=lambda pair: (int(pair[1].get("city") or 0), pair[1].get("tagname") or pair[0]))
def apply(pair):
key, stage = pair
city_id = str(int(stage.get("city") or 0))
if city_id not in cities:
name = self.catalog.data["game_setting"].get("cityInfo", {}).get(city_id, {}).get("name", f"地区 {city_id}")
cities[city_id] = TreeItem(self.tree, [name])
city = cities[city_id]
item = TreeItem(city, [f"{stage.get('tagname') or key} {stage.get('name') or key}"])
levels = sorted(stage.get("level", {}), key=lambda value: int(value))
item.setData(0, C.Qt.ItemDataRole.UserRole, (key, levels[-1]) if levels else None)
item.setToolTip(0, item.text(0) + f"\n关卡编号:{key}")
self.stage_items[key] = item
for level in levels:
child = TreeItem(item, [f"难度 {level}"])
child.setData(0, C.Qt.ItemDataRole.UserRole, (key, str(level)))
self.level_items[key, str(level)] = child
self.row_batch.start(rows, apply, self.finish_tree)
def finish_tree(self):
self.building = False
self.update_counts()
def update_counts(self):
for (stage, level), item in self.level_items.items():
for column, kind in ((1, "sweep"), (2, "event")):
count = self.count(stage, level, kind)
item.setText(column, str(count))
item.setTextAlignment(column, C.Qt.AlignmentFlag.AlignCenter)
for stage, item in self.stage_items.items():
for column in (1, 2):
item.setText(column, str(sum(int(item.child(i).text(column) or 0) for i in range(item.childCount()))))
item.setTextAlignment(column, C.Qt.AlignmentFlag.AlignCenter)
self.filter_tree()
if self.current_key in self.level_items:
self.tree.setCurrentItem(self.level_items[self.current_key])
if self.current_key is None:
first = next((key for key in self.level_items if any(self.count(*key, kind) for kind in ("sweep", "event"))), None)
if first:
item = self.level_items[first]
item.parent().setExpanded(True)
item.parent().parent().setExpanded(True)
self.tree.setCurrentItem(item)
def filter_tree(self):
query = self.search.text().strip().casefold()
for key, item in self.stage_items.items():
item.setHidden(bool(query and query not in (key + " " + item.text(0)).casefold()))
if query and not item.isHidden():
item.setExpanded(True)
item.parent().setExpanded(True)
for i in range(self.tree.topLevelItemCount()):
city = self.tree.topLevelItem(i)
city.setHidden(all(city.child(j).isHidden() for j in range(city.childCount())))
def selection_changed(self, item, previous=None):
if item is not None:
self.current_key = item.data(0, C.Qt.ItemDataRole.UserRole)
self.render_detail()
def render_detail(self, *args):
self.table.setSortingEnabled(False)
self.table.setRowCount(0)
chart = QChart()
chart.setAnimationOptions(QChart.AnimationOption.NoAnimation)
chart.setBackgroundRoundness(0)
chart.legend().hide()
chart.setFont(self.font())
chart.setMargins(C.QMargins(4, 4, 4, 4))
if self.palette().color(G.QPalette.ColorRole.Window).lightness() < 128:
chart.setTheme(QChart.ChartTheme.ChartThemeDark)
rows = []
metric = self.chart_metric.currentData()
if self.current_key:
stage_id, level = self.current_key
stage = self.catalog.data["stage_info"][stage_id]
totals, rows = analyze(self.catalog, self.data, stage_id, level, self.source.currentData())
counts = f"扫荡 {self.count(stage_id, level, 'sweep')} 次 / 事件 {self.count(stage_id, level, 'event')} 次"
average = f";平均金币 {totals['money']/totals['n']:.2f}、经验 {totals['exp']/totals['n']:.2f}" if totals["n"] else ";尚无此范围的样本,完成结算后自动记录"
self.summary.setText(f"{stage.get('tagname') or stage_id} {stage.get('name') or stage_id} / 难度 {level} | {counts}\n{self.source.currentText()}:{totals['n']} 个已确认样本;累计金币 {totals['money']}、经验 {totals['exp']}{average}\n已知体力消耗样本 {totals['known']}/{totals['n']};消耗体力 {totals['spent']};奖励返还体力 {totals['ti']}" + ("\n" + self.data["error"] if self.data.get("error") else ""))
chart.setTitle(self.chart_metric.currentText() if totals["n"] else "尚无样本")
self.table.setRowCount(len(rows))
kinds = {"item": "物品", "egg": "魔物蛋", "monster": "魔物"}
for i, row in enumerate(rows):
confidence = row["interval"]
values = [row["name"], kinds[row["kind"]], row["hits"], row["units"], row["samples"],
f"{row['rate']*100:.2f}%" if row["rate"] is not None else "—",
f"{row['average']:.3f}" if row["average"] is not None else "—",
f"{row['per_stamina']:.6g}" if row["per_stamina"] is not None else "—",
f"{confidence[0]*100:.1f}%~{confidence[1]*100:.1f}%" if confidence else "—",
"可能掉落" if row["configured"] else "实际观测"]
for column, value in enumerate(values):
item = table_item(value, column)
if column == 5:
item.setData(SORT_ROLE, row["rate"] if row["rate"] is not None else -1)
elif column == 7:
item.setData(SORT_ROLE, row["per_stamina"] if row["per_stamina"] is not None else -1)
self.table.setItem(i, column, item)
if totals["n"] and rows and any(row[metric] is not None for row in rows):
graph_rows = sorted(rows, key=lambda row: row[metric] or 0)
series = QHorizontalBarSeries()
bars = QBarSet(self.chart_metric.currentText())
values = [(row[metric] or 0) * (100 if metric == "rate" else 1) for row in graph_rows]
bars.append(values)
series.append(bars)
chart.addSeries(series)
x_axis, y_axis = QValueAxis(), QBarCategoryAxis()
x_axis.setRange(0, 100 if metric == "rate" else max(max(values) * 1.15, .001))
x_axis.setLabelFormat("%.0f%%" if metric == "rate" else "%.3g")
x_axis.setTitleText("出现次数 / 已确认样本数" if metric == "rate" else "获得数量 / 实际扣除体力")
names = [row["name"] for row in graph_rows]
y_axis.append([row["name"] if names.count(row["name"]) == 1 else f"{row['name']} #{row['typeId']}" for row in graph_rows])
chart.addAxis(x_axis, C.Qt.AlignmentFlag.AlignBottom)
chart.addAxis(y_axis, C.Qt.AlignmentFlag.AlignLeft)
series.attachAxis(x_axis)
series.attachAxis(y_axis)
series.hovered.connect(lambda active, index, barset: W.QToolTip.showText(G.QCursor.pos(),
f"{graph_rows[index]['name']}:" + (f"{graph_rows[index]['hits']}/{totals['n']} = {graph_rows[index]['rate']*100:.2f}%" if metric == "rate" else f"每点体力 {graph_rows[index]['per_stamina']:.6g} 个")) if active else W.QToolTip.hideText())
elif totals["n"] and metric == "per_stamina":
chart.setTitle("没有已知的非零体力消耗,暂不计算体力效率")
else:
self.summary.setText(self.data.get("error") or "请选择左侧的关卡和难度;关卡列表来自本地配置,不请求服务器。")
chart.setTitle("选择关卡后显示实测掉落率")
self.table.setSortingEnabled(True)
self.chart_view.setMinimumHeight(max(200, min(1400, len(rows) * 32 + 100)))
old = self.chart_view.chart()
self.chart_view.setChart(chart)
if old:
old.deleteLater()
+102 -2
View File
@@ -2,9 +2,16 @@
from dataclasses import dataclass, field
import json
from pathlib import Path
import sqlite3
import uuid
from .daily import day
from .maps import stages
from .drop_statistics import SweepStatistics, event_reward, normalize_reward
def settled_reward_event(response):
return event_reward(response) is not None
@dataclass
@@ -20,6 +27,82 @@ class SweepRunner:
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}
self.last_outcome = ""
self.recovery_checked = False
self.recovered_event = False
self.statistics = SweepStatistics(catalog, self.path.with_name("sweep_rewards.sqlite3") if self.path else None)
self.last_reward = None
self.statistics_error = ""
def remember_reward(self, client, snapshot, stage, kind, reward, response):
self.last_outcome = kind
self.last_reward = None
self.statistics_error = ""
try:
self.last_reward = normalize_reward(self.catalog, reward)
source = "run:" + self.state["pending"]["sampleId"]
operation = "stageService/stageStart" if kind == "event" else "battleService/battleEnd"
for event in reversed(getattr(getattr(client, "trace", None), "events", [])):
if event.get("operation") == operation and event.get("kind") == "response" and event.get("request_id"):
source = "request:" + event["request_id"]
break
cost = (response.get("stageEvent") or {}).get("costTi") if kind == "event" else response.get("costTi")
self.statistics.record(snapshot.raw["master"]["id"], stage.stage_id, stage.level, kind, source,
snapshot.now, reward, cost)
except (OSError, sqlite3.Error, ValueError, TypeError) as error:
# A local statistics failure must never repeat an awarded request.
self.statistics_error = "奖励统计未写入:" + str(error)
def recover_reward_event(self, snapshot, trace_path):
"""Repair only old reward-event blocks with a role-matched log reply.
This never replays a start or settlement request. Missing/ambiguous
evidence leaves the pending record intact.
"""
pending = self.state.get("pending")
if (self.recovery_checked or not trace_path or not pending
or pending.get("phase") != "遇到事件或响应缺少事件状态,请在游戏内处理"):
return False
self.recovery_checked = True
role, requests, last_reply = None, {}, None
owner = snapshot.raw["master"]["id"]
path = Path(trace_path)
try:
for file in (path.with_name("network_debug.previous.jsonl"), path):
if not file.exists():
continue
with file.open(encoding="utf-8") as stream:
for line in stream:
try:
event = json.loads(line)
except ValueError:
continue
body = event.get("body")
if not isinstance(body, dict):
continue
if event.get("operation") == "读取角色" and event.get("kind") == "response":
role = (body.get("master") or {}).get("id")
if event.get("operation") != "stageService/stageStart":
continue
identifier = event.get("request_id")
if not isinstance(identifier, str) or not identifier:
continue
if event.get("kind") == "request":
matched = (str(role) == str(owner) and str(body.get("stageTypeId")) == pending["stage"]
and str(body.get("stageLevel")) == str(pending["level"]))
requests[identifier] = matched
if matched:
last_reply = None
elif event.get("kind") == "response" and requests.get(identifier):
last_reply = body if event.get("http_status") == 200 and body.get("resCode") in (0, "0") else None
except (OSError, ValueError, TypeError, AttributeError):
return False
if last_reply and settled_reward_event(last_reply):
self.state["pending"] = None
self.save()
self.recovered_event = True
return True
return False
def save(self):
if self.path:
@@ -78,6 +161,8 @@ class SweepRunner:
return None
def run(self, client, snapshot, stage, policy):
self.last_outcome = ""
self.last_reward = None
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("此关卡未勾选或已达本日次数上限")
@@ -86,12 +171,25 @@ class SweepRunner:
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.state["pending"] = {"stage": stage.stage_id, "level": stage.level, "phase": "开始请求待确认", "sampleId": uuid.uuid4().hex}
self.save() # Reserve before the first non-retryable write, including timeouts.
started = client.call("stageService/stageStart", {"stageTypeId": stage.stage_id, "stageLevel": stage.level})
if settled_reward_event(started):
# StageCenter.startStageHandler applies stageEvent.result directly;
# StageStartPanel shows it and returns, without battleEnd.
self.remember_reward(client, snapshot, stage, "event", started["stageEvent"]["result"], started)
self.state["pending"] = None
self.save()
self.last_outcome = "event"
return started
flag = started.get("triggerEvent")
if flag is not False and not (type(flag) is int and flag == 0):
self.state["pending"]["phase"] = "遇到事件或响应缺少事件状态,请在游戏内处理"
event = started.get("stageEvent")
if isinstance(event, dict) and event.get("hideStageId") is not None:
phase = "遭遇隐藏关卡,请在游戏内手动战斗"
else:
phase = "事件结果或开始状态尚未确认,请在游戏内检查"
self.state["pending"]["phase"] = phase
self.save()
raise ValueError(self.state["pending"]["phase"])
# Exactly the official doSaodangBattle data; only for its eligible stages.
@@ -101,7 +199,9 @@ class SweepRunner:
self.state["pending"]["phase"] = "扫荡结算待确认"
self.save()
result = client.call("battleService/battleEnd", {"battleData": battle})
self.remember_reward(client, snapshot, stage, "sweep", result.get("reward"), result)
self.state["pending"] = None
self.save()
client.call("battleService/recordBattleResult", {"stageId": stage.stage_id, "cityId": stage.stage_id[1:2], "result": 1})
self.last_outcome = "sweep"
return result
+89
View File
@@ -0,0 +1,89 @@
"""Native table alignment and sorting for embedded rule editors."""
import re
from PySide6 import QtCore as C, QtWidgets as W
SORT_ROLE = C.Qt.ItemDataRole.UserRole + 20
def alignment(column):
return C.Qt.AlignmentFlag.AlignVCenter | (C.Qt.AlignmentFlag.AlignLeft if column < 2 else C.Qt.AlignmentFlag.AlignHCenter)
def sort_key(value):
if isinstance(value, (int, float)):
return (0, value)
parts = re.split(r"(\d+)", str(value or "").casefold())
return (1, tuple((0, int(part)) if part.isdigit() else (1, part) for part in parts))
class TableItem(W.QTableWidgetItem):
def __lt__(self, other):
def value(item):
result = item.data(SORT_ROLE)
return item.data(C.Qt.ItemDataRole.DisplayRole) if result is None else result
return sort_key(value(self)) < sort_key(value(other))
class TreeItem(W.QTreeWidgetItem):
def __lt__(self, other):
column = self.treeWidget().sortColumn()
def value(item):
result = item.data(column, SORT_ROLE)
return item.data(column, C.Qt.ItemDataRole.DisplayRole) if result is None else result
return sort_key(value(self)) < sort_key(value(other))
class CenteredCheckBox(W.QCheckBox):
def paintEvent(self, event):
painter = W.QStylePainter(self)
option = W.QStyleOptionButton()
self.initStyleOption(option)
indicator = self.style().subElementRect(W.QStyle.SubElement.SE_CheckBoxIndicator, option, self)
option.rect.setLeft((self.width() - indicator.width()) // 2)
option.rect.setWidth(indicator.width())
painter.drawControl(W.QStyle.ControlElement.CE_CheckBox, option)
def hitButton(self, position):
return self.rect().contains(position)
def set_value(item, column, value):
if isinstance(item, W.QTreeWidgetItem):
item.setData(column, C.Qt.ItemDataRole.DisplayRole, value)
item.setTextAlignment(column, alignment(column))
else:
item.setData(C.Qt.ItemDataRole.DisplayRole, value)
item.setTextAlignment(alignment(column))
def table_item(value, column):
item = TableItem()
set_value(item, column, value)
return item
def bind_controls(view, row, controls):
"""Keep a stable item reference: a control edit can move its row immediately."""
for column, control in controls.items():
item = row if isinstance(row, W.QTreeWidgetItem) else view.item(row, column)
control._sort_binding = (item, column)
if isinstance(control, W.QLineEdit):
control.setAlignment(alignment(column))
elif isinstance(control, W.QComboBox):
control.setTextAlignment(alignment(column))
if not getattr(control, "_sort_connected", False):
def update(*args, control=control):
item, column = control._sort_binding
value = (int(control.isChecked()) if isinstance(control, W.QCheckBox) else
control.currentText() if isinstance(control, W.QComboBox) else control.value())
if isinstance(item, W.QTreeWidgetItem):
item.setData(column, SORT_ROLE, value)
else:
item.setData(SORT_ROLE, value)
signal = (control.toggled if isinstance(control, W.QCheckBox) else
control.currentIndexChanged if isinstance(control, W.QComboBox) else control.valueChanged)
signal.connect(update)
control._sort_connected = True
control._update_sort = update
control._update_sort()
@@ -0,0 +1,210 @@
import json
import os
from pathlib import Path
import threading
import unittest
from unittest.mock import patch
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6 import QtCore as C, QtWidgets as W
from PySide6.QtTest import QTest
from ranch_assistant.account_storage import profile_directory, remove_account_files
from ranch_assistant.accounts_gui import AccountsWindow
from ranch_assistant.tests.test_core import workspace_temp
class RemovalTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.app = W.QApplication.instance() or W.QApplication([])
def wait(self, predicate):
for _ in range(1000):
self.app.processEvents()
QTest.qWait(2)
if predicate():
return
self.fail("Account shutdown did not finish")
def idle(self, hub):
for window in hub.windows.values():
window.timer.stop()
self.wait(lambda: all(not w.busy and w.engine.snapshot is not None for w in hub.windows.values()))
def remove(self, hub, identifier):
with patch.object(W.QMessageBox, "question", return_value=W.QMessageBox.StandardButton.Yes):
hub.confirm_remove_profile(identifier)
def test_close_all_remains_closed_and_manual_reopen_is_persisted(self):
with workspace_temp() as folder:
hub = AccountsWindow(folder)
self.idle(hub)
hub.close_profile(0)
hub.close()
hub = AccountsWindow(folder)
try:
self.assertEqual(hub.tabs.count(), 0)
self.assertEqual(len(hub.profiles), 1)
hub.open_profile(hub.profiles[0])
self.idle(hub)
hub.close()
hub = AccountsWindow(folder)
self.idle(hub)
self.assertEqual(hub.tabs.count(), 1)
finally:
hub.close()
def test_remove_closed_account_deletes_only_its_workspace_and_stays_removed(self):
with workspace_temp() as folder:
hub = AccountsWindow(folder)
hub.add_profile()
self.idle(hub)
identifier = hub.profiles[-1]["id"]
target = profile_directory(folder, identifier)
hub.close_profile(hub.tabs.count() - 1)
(target / "sessions").mkdir()
(target / "sessions" / "test.json").write_text("synthetic session", encoding="utf-8")
protected = folder / "credentials.json"
protected.write_text("{}", encoding="utf-8")
try:
self.remove(hub, identifier)
self.assertFalse(target.exists())
self.assertTrue(protected.exists())
self.assertIn("default", hub.windows)
self.assertFalse(any(p["id"] == identifier for p in hub.profiles))
hub.close()
hub = AccountsWindow(folder)
self.idle(hub)
self.assertFalse(any(p["id"] == identifier for p in hub.profiles))
self.assertNotIn(identifier, hub.windows)
finally:
hub.close()
def test_remove_default_preserves_other_accounts_registry_and_shared_files(self):
with workspace_temp() as folder:
hub = AccountsWindow(folder)
hub.add_profile()
self.idle(hub)
other = hub.profiles[-1]["id"]
sentinel = profile_directory(folder, other) / "keep.txt"
sentinel.write_text("another account", encoding="utf-8")
(folder / "sessions").mkdir()
(folder / "sessions" / "old.json").write_text("synthetic", encoding="utf-8")
(folder / "roles" / "role").mkdir(parents=True)
(folder / "roles" / "role" / "maps.json").write_text("{}", encoding="utf-8")
(folder / "sweep_rewards.sqlite3").write_text("synthetic statistics", encoding="utf-8")
(folder / "cultivation_choices.json").write_text("{}", encoding="utf-8")
shared = folder / "shared-note.txt"
shared.write_text("keep", encoding="utf-8")
try:
self.remove(hub, "default")
for name in ("credentials.json", "sessions", "roles", "settings.json", "sweep_rewards.sqlite3", "cultivation_choices.json"):
self.assertFalse((folder / name).exists())
self.assertTrue(sentinel.exists())
self.assertTrue(shared.exists())
self.assertTrue(hub.index_path.exists())
self.assertEqual([p["id"] for p in hub.profiles], [other])
hub.close()
hub = AccountsWindow(folder)
self.idle(hub)
self.assertNotIn("default", hub.windows)
self.assertIn(other, hub.windows)
finally:
hub.close()
def test_cancel_removal_keeps_live_account_untouched(self):
with workspace_temp() as folder:
hub = AccountsWindow(folder)
self.idle(hub)
try:
with patch.object(W.QMessageBox, "question", return_value=W.QMessageBox.StandardButton.No):
hub.confirm_remove_profile("default")
self.assertIn("default", hub.windows)
self.assertFalse(hub.windows["default"].closed)
self.assertTrue(hub.profiles[0]["open"])
finally:
hub.close()
def test_busy_account_is_removed_only_after_worker_finishes_without_recreating_records(self):
with workspace_temp() as folder:
hub = AccountsWindow(folder)
self.idle(hub)
window = hub.windows["default"]
release, started = threading.Event(), threading.Event()
def work():
started.set()
release.wait(3)
return "synthetic completed job"
try:
window.submit("test", work)
self.wait(started.is_set)
self.remove(hub, "default")
self.assertIn("default", hub.windows)
self.assertIn("default", hub.pending_removals)
self.assertFalse(window.strategy_toggle.isChecked())
self.assertFalse(window.monitoring)
release.set()
self.wait(lambda: not hub.windows and not hub.pending_removals)
QTest.qWait(400)
self.assertFalse((folder / "settings.json").exists())
self.assertFalse((folder / "credentials.json").exists())
self.assertEqual(json.loads(hub.index_path.read_text(encoding="utf-8"))["profiles"], [])
hub.close()
hub = AccountsWindow(folder)
self.assertEqual(hub.tabs.count(), 0)
self.assertEqual(hub.profiles, [])
finally:
release.set()
self.idle(hub)
hub.close()
def test_external_lock_blocks_removal_and_keeps_account_in_registry(self):
with workspace_temp() as folder:
hub = AccountsWindow(folder)
hub.add_profile()
self.idle(hub)
identifier = hub.profiles[-1]["id"]
hub.close_profile(hub.tabs.count() - 1)
target = profile_directory(folder, identifier)
lock = C.QLockFile(str(target / "workspace.lock"))
self.assertTrue(lock.tryLock(0))
try:
self.remove(hub, identifier)
self.assertTrue(target.exists())
self.assertTrue(any(p["id"] == identifier for p in hub.profiles))
self.assertIn("其他窗口", hub.statusBar().currentMessage())
finally:
lock.unlock()
hub.close()
def test_failed_file_removal_keeps_registry_for_retry(self):
with workspace_temp() as folder:
hub = AccountsWindow(folder)
self.idle(hub)
try:
with patch("ranch_assistant.accounts_gui.remove_account_files", side_effect=OSError("synthetic failure")):
self.remove(hub, "default")
self.assertTrue(any(p["id"] == "default" for p in hub.profiles))
self.assertIn("未完全移除", hub.statusBar().currentMessage())
finally:
hub.close()
def test_profile_deletion_rejects_invalid_identifier_and_directory_links(self):
with workspace_temp() as folder, workspace_temp() as outside:
for identifier in ("..", "profiles", "../outside", "", None):
with self.assertRaises(ValueError):
profile_directory(folder, identifier)
(folder / "profiles").mkdir()
target = folder / "profiles" / ("a" * 32)
try:
target.symlink_to(outside, target_is_directory=True)
except OSError:
return # Some Windows installations do not permit symlinks.
try:
(outside / "keep.txt").write_text("keep", encoding="utf-8")
with self.assertRaises(ValueError):
remove_account_files(folder, "a" * 32)
self.assertTrue((outside / "keep.txt").exists())
finally:
target.unlink()
+191 -10
View File
@@ -117,6 +117,83 @@ class AccountGuiTests(unittest.TestCase):
window.result("connected", (client, Snapshot(role_snapshot(window.catalog, role_id))))
return client
def test_main_menu_routes_strategy_actions_to_selected_account_and_saves_immediately(self):
with workspace_temp() as folder:
hub = AccountsWindow(folder)
hub.add_profile()
windows = list(hub.windows.values())
for window in windows:
window.timer.stop()
try:
self.wait(windows)
first, second = windows
first.keep_money.setValue(1234)
second.keep_money.setValue(5678)
for window in windows:
window.auto_save_timer.stop()
for selected, other, expected in ((first, second, 1234), (second, first, 5678)):
hub.tabs.setCurrentWidget(selected)
with patch.object(selected, "import_policies") as imported, patch.object(other, "import_policies") as other_imported:
hub.import_policy_action.trigger()
imported.assert_called_once_with()
other_imported.assert_not_called()
with patch.object(selected, "export_policies") as exported, patch.object(other, "export_policies") as other_exported:
hub.export_policy_action.trigger()
exported.assert_called_once_with()
other_exported.assert_not_called()
with patch.object(other, "persist_settings") as other_saved:
hub.save_policy_action.trigger()
other_saved.assert_not_called()
saved = json.loads((selected.state / "settings.json").read_text(encoding="utf-8"))
self.assertEqual(saved["policy"]["keep_money"], expected)
self.assertEqual(selected.engine.policy.keep_money, expected)
self.assertFalse(selected.strategy_toggle.isChecked())
finally:
hub.close()
def test_only_main_window_has_menus_and_about_shows_versions(self):
with workspace_temp() as folder:
hub = AccountsWindow(folder)
windows = list(hub.windows.values())
for window in windows:
window.timer.stop()
try:
self.wait(windows)
self.assertEqual([action.text().split("(")[0] for action in hub.menuBar().actions()],
["账号", "策略", "策略配置", "帮助"])
for window in windows:
self.assertIsNone(window.findChild(W.QMenuBar))
labels = {button.text() for button in hub.findChildren(W.QPushButton)}
for label in ("新增账号页签", "打开已保存账号", "恢复各页签的保存会话", "全部开始监控", "全部停止"):
self.assertNotIn(label, labels)
with patch.object(W.QMessageBox, "about") as about:
hub.about_action.trigger()
self.assertIn(gui.APP_VERSION, about.call_args.args[2])
self.assertIn(gui.GAME_VERSION, about.call_args.args[2])
self.assertNotIn("开发中", about.call_args.args[2])
finally:
hub.close()
def test_strategy_menu_disables_when_no_account_is_open(self):
with workspace_temp() as folder:
hub = AccountsWindow(folder)
windows = list(hub.windows.values())
for window in windows:
window.timer.stop()
try:
self.wait(windows)
hub.close_profile(0)
self.assertEqual(hub.tabs.count(), 0)
self.assertTrue(all(not action.isEnabled() for action in hub.policy_actions))
hub.add_profile()
windows = list(hub.windows.values())
for window in windows:
window.timer.stop()
self.wait(windows)
self.assertTrue(all(action.isEnabled() for action in hub.policy_actions))
finally:
hub.close()
def test_closed_fresh_tab_does_not_start_queued_refresh_and_can_reopen(self):
with workspace_temp() as folder:
hub = AccountsWindow(folder)
@@ -132,6 +209,31 @@ class AccountGuiTests(unittest.TestCase):
finally:
hub.close()
def test_closed_tab_stays_closed_after_restart_and_can_be_opened_manually(self):
with workspace_temp() as folder:
hub = AccountsWindow(folder)
hub.add_profile()
for window in hub.windows.values():
window.timer.stop()
self.wait(list(hub.windows.values()))
closed = hub.profiles[-1]
hub.close_profile(hub.tabs.count() - 1)
hub.close()
restarted = AccountsWindow(folder)
for window in restarted.windows.values():
window.timer.stop()
try:
self.wait(list(restarted.windows.values()))
self.assertNotIn(closed["id"], restarted.windows)
self.assertTrue(any(p["id"] == closed["id"] for p in restarted.profiles))
restarted.open_profile(next(p for p in restarted.profiles if p["id"] == closed["id"]))
for window in restarted.windows.values():
window.timer.stop()
self.wait(list(restarted.windows.values()))
self.assertIn(closed["id"], restarted.windows)
finally:
restarted.close()
def test_failed_resume_saves_counters_before_response_and_keeps_execution_off(self):
with workspace_temp() as folder:
window = gui.Window(folder)
@@ -149,7 +251,7 @@ class AccountGuiTests(unittest.TestCase):
window.resume_session()
self.wait([window])
self.assertEqual(window.session_store.load(key).reqid, 1)
self.assertFalse(window.execute.isChecked())
self.assertFalse(window.strategy_toggle.isChecked())
self.assertTrue(window.engine.demo)
finally:
window.close()
@@ -172,12 +274,14 @@ class AccountGuiTests(unittest.TestCase):
hub.tabs.setCurrentWidget(first)
for page in (first.egg_page, first.monster_page, first.room_page):
first.tabs.setCurrentWidget(page)
self.assertEqual([first.slots.rowCount(), first.eggs.rowCount(), first.monsters.rowCount(), first.rooms_table.rowCount()], [11, 4, 4, 1])
self.assertEqual([first.slots.rowCount(), first.eggs.rowCount(), len(first.monsters.monster_items)], [11, 4, 4])
self.assertFalse(first.monsters.group_items)
self.assertTrue(all(item.parent() is None for item in first.monsters.monster_items.values()))
self.assertEqual(first.saved_sessions.count(), 1)
first.start_monitor.setChecked(True)
first.monitoring = True
hub.tabs.setCurrentWidget(second)
self.assertTrue(first.monitoring)
hub.monitor_all()
self.assertTrue(all(window.monitoring for window in windows))
for window in windows:
window.engine.last_heartbeat = time.monotonic()
window.next_poll = 0
@@ -188,7 +292,7 @@ class AccountGuiTests(unittest.TestCase):
self.assertEqual(second.engine.client.session.token, "test-token-account-b")
self.assertEqual(first.engine.snapshot.raw["master"]["id"], 101)
self.assertEqual(second.engine.snapshot.raw["master"]["id"], 202)
first.execute.setChecked(True)
first.set_strategy_checked(True)
before = len(calls)
hub.tabs.setCurrentWidget(first)
first.tabs.setCurrentWidget(first.egg_page)
@@ -204,10 +308,6 @@ class AccountGuiTests(unittest.TestCase):
self.assertTrue(all(url.endswith("masterService/masterQueryDetail") for _, url, _ in calls[before:]))
self.assertFalse(first.engine.auto)
self.assertIs(first.tabs.currentWidget(), first.egg_page)
first.farm.running = True
first.farm.adb.serial = "phone-a"
self.assertFalse(hub.allow_device(second, "phone-a"))
self.assertTrue(hub.allow_device(second, "phone-b"))
self.assertFalse(hub.allow_login(second, "account-a"))
self.assertFalse(hub.allow_connection(second, first.engine.client.session))
finally:
@@ -225,10 +325,90 @@ class AccountGuiTests(unittest.TestCase):
self.wait(restarted)
self.assertEqual({window.engine.snapshot.raw["master"]["id"] for window in restarted}, {101, 202},
"\n".join(window.log.toPlainText() for window in restarted))
self.assertTrue(all(not window.engine.demo and not window.execute.isChecked() and not window.monitoring for window in restarted))
self.assertTrue(all(not window.engine.demo and not window.strategy_toggle.isChecked() and window.monitoring for window in restarted))
finally:
restored.close()
def test_login_refreshes_automatically_and_strategy_menu_only_controls_execution(self):
with workspace_temp() as folder:
hub = AccountsWindow(folder)
hub.add_profile()
windows = list(hub.windows.values())
calls = []
for window in windows:
window.timer.stop()
try:
self.wait(windows)
for number, window in enumerate(windows, 1):
self.connect(window, f"account-{number}", number, number, calls)
self.assertTrue(window.monitoring)
self.assertFalse(window.strategy_toggle.isChecked())
window.engine.last_heartbeat = time.monotonic()
window.schedule()
self.wait(windows)
self.assertTrue(calls)
self.assertTrue(all(url.endswith("masterService/masterQueryDetail") for _, url, _ in calls))
for window in windows:
window.ranch_enabled.setChecked(False)
window.daily_enabled.setChecked(True)
# Exercise real Qt menu actions with synthetic worker results.
observed = []
from contextlib import ExitStack
with ExitStack() as stack:
for window in windows:
def poll(current=window, **kwargs):
observed.append((current, current.engine.auto))
return current.engine.snapshot, [], "synthetic refresh"
stack.enter_context(patch.object(window.engine, "poll", side_effect=poll))
menu = next(action.menu() for action in hub.menuBar().actions() if action.text() == "策略(&R)")
menu.actions()[0].trigger()
self.wait(windows)
self.assertEqual(len(observed), 2)
self.assertTrue(all(enabled for _, enabled in observed))
self.assertTrue(all(w.strategy_toggle.text() == "关闭策略" for w in windows))
# A manual refresh never executes, even with strategies on.
windows[0].refresh()
self.wait(windows)
self.assertFalse(observed[-1][1])
menu.actions()[1].trigger()
self.assertTrue(all(w.monitoring and not w.strategy_toggle.isChecked() for w in windows))
observed.clear()
for window in windows:
window.next_poll = 0
window.schedule()
self.wait(windows)
self.assertEqual(len(observed), 2)
self.assertFalse(any(enabled for _, enabled in observed))
windows[0].demo()
self.wait(windows)
self.assertFalse(windows[0].monitoring)
self.assertTrue(windows[1].monitoring)
finally:
hub.close()
def test_incomplete_policy_keeps_logged_in_account_refreshing_without_actions(self):
with workspace_temp() as folder:
window = gui.Window(folder)
window.timer.stop()
calls = []
try:
self.wait([window])
self.connect(window, "account-a", 1, 101, calls)
window.reserved_types.setText("incomplete-input")
window.strategy_toggle.click()
self.assertFalse(window.strategy_toggle.isChecked())
self.assertTrue(window.monitoring)
window.engine.last_heartbeat = time.monotonic()
window.next_poll = 0
window.schedule()
self.wait([window])
self.assertTrue(window.monitoring)
self.assertFalse(window.engine.auto)
self.assertTrue(calls)
self.assertTrue(all(url.endswith("masterService/masterQueryDetail") for _, url, _ in calls))
finally:
window.close()
def test_role_switch_restores_own_strategy_and_heartbeat_uses_normal_api(self):
with workspace_temp() as folder:
window = gui.Window(folder)
@@ -247,6 +427,7 @@ class AccountGuiTests(unittest.TestCase):
self.assertEqual(window.strategy.currentData(), "gold")
self.assertEqual(window.saved_sessions.count(), 2)
window.engine.last_heartbeat = 0
window.next_poll = float("inf")
window.schedule()
self.wait([window])
self.assertTrue(calls[-1][1].endswith("heartBeatService/keepAlive"))
+60 -6
View File
@@ -19,6 +19,9 @@ def scenario():
# 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)
for mon in snapshot.raw["monsters"]:
if mon.get("process") == 2:
mon["mode"] = snapshot.expected_growth_mode(mon, 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]}]
@@ -109,6 +112,54 @@ class ActivityTests(unittest.TestCase):
runner.run(client, self.snapshot, self.stage(), policy)
self.assertTrue(SweepRunner(self.catalog, folder / "runs.json").state["pending"])
def test_reward_event_is_already_settled_and_does_not_block_next_sweep(self):
runner = SweepRunner(self.catalog)
policy = SweepPolicy(True, {"0101": {"enabled": True, "level": "3", "limit": 3}})
client = FakeClient(self.snapshot)
response = {"resCode": 0, "triggerEvent": True, "stageEvent": {"resCode": 0,
"typeId": "300007", "hideStageId": None, "costTi": 16,
"result": {"money": 32, "exp": 64, "items": [], "monsters": [], "ti": 0, "ke": 0}}}
def call(path, payload=None):
client.calls.append((path, payload))
if path == "stageService/stageStart":
return response
raise AssertionError("Reward events do not submit a battle result")
client.call = call
result = runner.run(client, self.snapshot, self.stage(), policy)
self.assertIs(result, response)
self.assertIsNone(runner.state["pending"])
self.assertIsNotNone(runner.next(self.snapshot, policy))
self.assertEqual(len(client.calls), 1)
def test_legacy_event_block_recovers_only_from_role_matched_successful_reward_reply(self):
with workspace_temp() as folder:
trace = folder / "network_debug.jsonl"
for role, hidden, http_status, recovered in ((123456, None, 200, False),
(self.snapshot.raw["master"]["id"], "hidden", 200, False),
(self.snapshot.raw["master"]["id"], None, 500, False),
(self.snapshot.raw["master"]["id"], None, 200, True)):
runner = SweepRunner(self.catalog)
runner.state["pending"] = {"stage": "0101", "level": "3", "phase": "遇到事件或响应缺少事件状态,请在游戏内处理"}
records = [{"kind": "response", "operation": "读取角色", "body": {"master": {"id": role}}},
{"kind": "request", "operation": "stageService/stageStart", "request_id": "test-1",
"body": {"stageTypeId": "0101", "stageLevel": "3"}},
{"kind": "response", "operation": "stageService/stageStart", "request_id": "test-1", "http_status": http_status,
"body": {"resCode": 0, "triggerEvent": True, "stageEvent": {"hideStageId": hidden, "result": {"money": 32}}}}]
trace.write_text("\n".join(json.dumps(row) for row in records), encoding="utf-8")
self.assertEqual(runner.recover_reward_event(self.snapshot, trace), recovered)
self.assertEqual(runner.state["pending"] is None, recovered)
def test_hidden_stage_event_waits_for_real_battle_without_submitting_a_result(self):
runner = SweepRunner(self.catalog)
policy = SweepPolicy(True, {"0101": {"enabled": True, "level": "3", "limit": 3}})
client = FakeClient(self.snapshot)
client.call = unittest.mock.Mock(return_value={"resCode": 0, "triggerEvent": True,
"stageEvent": {"hideStageId": "hidden", "result": {"money": 1}}})
with self.assertRaisesRegex(ValueError, "隐藏关卡"):
runner.run(client, self.snapshot, self.stage(), policy)
client.call.assert_called_once_with("stageService/stageStart", {"stageTypeId": "0101", "stageLevel": "3"})
self.assertIsNone(runner.next(self.snapshot, policy))
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)
@@ -225,6 +276,11 @@ class ActivityGuiTests(unittest.TestCase):
window.engine = Engine(catalog)
window.engine.snapshot = snapshot
window.render_maps()
for _ in range(200):
if not window.map_render_timer.running:
break
QTest.qWait(5)
self.assertFalse(window.map_render_timer.running)
window.render_daily()
self.assertEqual(window.maps_tree.topLevelItem(0).text(0), "莉莉托斯")
region = window.maps_tree.topLevelItem(0)
@@ -241,13 +297,11 @@ class ActivityGuiTests(unittest.TestCase):
self.assertEqual(settings["sweep_policy"]["rules"]["0101"]["limit"], 12)
window.resize(1100, 650)
window.show()
window.tabs.setCurrentWidget(window.capture_scroll)
window.tabs.setCurrentWidget(window.automation_page)
window.automation_tabs.setCurrentWidget(window.policy_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.assertGreater(window.policy_scroll.verticalScrollBar().maximum(), 0)
self.assertEqual(window.styleSheet(), "")
finally:
window.close()
@@ -260,7 +314,7 @@ class ActivityGuiTests(unittest.TestCase):
if not restored.busy:
break
self.assertEqual(restored.map_rules["0101"]["limit"], 12)
self.assertFalse(restored.execute.isChecked())
self.assertFalse(restored.strategy_toggle.isChecked())
self.assertFalse(restored.monitoring)
finally:
restored.close()
+19 -12
View File
@@ -314,7 +314,7 @@ class AutomationGuiTests(unittest.TestCase):
return
self.fail("Qt task did not finish")
def test_workflow_start_monitor_stop_and_settings_restore(self):
def test_strategy_toggle_off_keeps_refreshing_and_settings_restore_with_strategy_off(self):
with workspace_temp() as folder:
window = gui.Window(folder)
window.timer.stop()
@@ -327,17 +327,24 @@ class AutomationGuiTests(unittest.TestCase):
window.fill.setChecked(False)
window.buy_eggs.setChecked(False)
before = len(window.engine.snapshot.raw["monsters"])
window.monitor_only()
window.refresh()
self.wait(window)
self.assertEqual(len(window.engine.snapshot.raw["monsters"]), before)
self.assertIn("仅监控", window.workflow_status.text())
window.workflow_start.click()
self.assertIn("策略已关闭", window.workflow_status.text())
window.strategy_toggle.click()
self.wait(window)
self.assertEqual(len(window.engine.snapshot.raw["monsters"]), before - 1)
self.assertIn("执行中", window.workflow_status.text())
window.workflow_stop.click()
self.assertIn("策略已开启", window.workflow_status.text())
window.strategy_toggle.click()
self.assertTrue(window.monitoring)
self.assertFalse(window.engine.auto)
self.assertEqual(window.strategy_toggle.text(), "开启策略")
remaining = len(window.engine.snapshot.raw["monsters"])
window.next_poll = 0
window.schedule()
self.wait(window)
self.assertEqual(len(window.engine.snapshot.raw["monsters"]), remaining)
self.assertFalse(window.engine.auto)
window.buy_eggs.setChecked(True)
window.market.setCurrentIndex(window.market.findData("sc_city2"))
window.daily_buy_money.setValue(700)
@@ -355,7 +362,7 @@ class AutomationGuiTests(unittest.TestCase):
self.assertTrue(restored.buy_eggs.isChecked())
self.assertEqual(restored.market.currentData(), "sc_city2")
self.assertEqual(restored.daily_buy_money.value(), 700)
self.assertFalse(restored.execute.isChecked())
self.assertFalse(restored.strategy_toggle.isChecked())
self.assertFalse(restored.yield_stars[5].isChecked())
self.assertEqual(restored.hatch_max_star.currentData(), 3)
finally:
@@ -413,19 +420,19 @@ class AutomationGuiTests(unittest.TestCase):
window.timer.stop()
try:
self.wait(window)
window.execute.setChecked(True)
window.start_monitor.setChecked(True)
window.set_strategy_checked(True)
window.monitoring = True
before = len(window.engine.snapshot.raw["monsters"])
def select(mid):
window.tabs.setCurrentWidget(window.monster_page)
row = next(i for i in range(window.monsters.rowCount()) if int(window.monsters.item(i, 0).text()) == mid)
window.monsters.selectRow(row)
window.monsters.clearSelection()
window.monsters.setCurrentItem(window.monsters.monster_items[mid])
select(101)
self.assertTrue(window.lock_monsters.isEnabled())
window.lock_monsters.click()
self.wait(window)
self.assertEqual(window.engine.snapshot.monsters[101]["lock"], 1)
self.assertFalse(window.execute.isChecked())
self.assertFalse(window.strategy_toggle.isChecked())
self.assertEqual(len(window.engine.snapshot.raw["monsters"]), before)
select(101)
with patch("PySide6.QtWidgets.QMenu.popup"):
+102
View File
@@ -0,0 +1,102 @@
import os
import unittest
from unittest.mock import patch
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6 import QtCore as C, QtGui as G, QtWidgets as W
from ranch_assistant.gui import combo, compact_layouts
from ranch_assistant.native_widgets import ComboBox, use_native_scrollbars
class ComboBoxTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.app = W.QApplication.instance() or W.QApplication([])
use_native_scrollbars()
def test_popup_fits_longest_option_despite_narrow_control_and_wide_scrollbar(self):
widget = combo([("随机30秒", 30), ("四项全S(4S)才保留", 6), ("随机2分钟", 120), ("随机5分钟", 300)])
widget.setStyle(W.QStyleFactory.create("Windows"))
self.assertGreaterEqual(widget.minimumSizeHint().width(), widget.fontMetrics().horizontalAdvance("四项全S(4S)才保留") + 40)
widget.setFixedWidth(100)
widget.show()
try:
self.app.processEvents()
widget.showPopup()
self.app.processEvents()
view = widget.view()
needed = max(view.fontMetrics().horizontalAdvance(widget.itemText(i)) for i in range(widget.count())) + 16
self.assertGreaterEqual(view.viewport().width(), needed)
finally:
widget.hidePopup()
widget.close()
def test_dynamic_options_remeasure_and_popup_stays_on_screen(self):
widget = ComboBox()
widget.setStyle(W.QStyleFactory.create("Windows"))
widget.addItem("派遣")
widget.setFixedWidth(100)
widget.show()
try:
widget.showPopup()
self.app.processEvents()
original = widget.view().window().width()
widget.hidePopup()
label = "莉莉托斯市场 · 每批十连 · 保留金币并限制每日额度"
widget.addItem(label)
widget.showPopup()
self.app.processEvents()
self.assertGreater(widget.view().window().width(), original)
self.assertGreaterEqual(widget.view().viewport().width(), widget.fontMetrics().horizontalAdvance(label) + 16)
self.assertTrue(widget.screen().availableGeometry().contains(widget.view().window().geometry()))
widget.hidePopup()
widget.setItemText(1, "短选项")
widget.showPopup()
self.app.processEvents()
self.assertLess(widget.view().window().width(), widget.fontMetrics().horizontalAdvance(label))
finally:
widget.hidePopup()
widget.close()
def test_screen_wide_labels_scroll_and_hover_keeps_full_text_and_help(self):
label = "魔物名称与编号" * 100
widget = combo([(label, 1)])
widget.setToolTip("保留策略说明")
widget.setFixedWidth(100)
widget.show()
try:
widget.showPopup()
self.app.processEvents()
self.assertLessEqual(widget.view().window().width(), widget.screen().availableGeometry().width())
self.assertGreater(widget.view().horizontalScrollBar().maximum(), 0)
widget.hidePopup()
event = G.QHelpEvent(C.QEvent.Type.ToolTip, C.QPoint(5, 5), widget.mapToGlobal(C.QPoint(5, 5)))
with patch.object(W.QToolTip, "showText") as tooltip:
self.app.sendEvent(widget, event)
self.assertEqual(tooltip.call_args.args[1], label + "\n保留策略说明")
finally:
widget.hidePopup()
widget.close()
def test_compact_page_layout_keeps_short_popup_options_fully_visible(self):
page = W.QWidget()
layout = W.QVBoxLayout(page)
widget = combo([("随机30秒", 30), ("随机60秒", 60), ("随机2分钟", 120), ("随机5分钟", 300)])
layout.addWidget(widget)
compact_layouts(page)
page.show()
try:
self.app.processEvents()
widget.showPopup()
self.app.processEvents()
view = widget.view()
last = view.visualRect(view.model().index(widget.count() - 1, 0))
self.assertLess(last.bottom(), view.viewport().height())
finally:
widget.hidePopup()
page.close()
if __name__ == "__main__":
unittest.main()
+2 -59
View File
@@ -11,11 +11,9 @@ import uuid
from unittest.mock import patch
import requests
from PIL import Image, ImageDraw
from ranch_assistant.api import ApiError, Client, DEFAULT_KEY, Session, decode, encode
from ranch_assistant.engine import Engine, demo_snapshot
from ranch_assistant.farming import FarmBudget, FarmConfig, FarmRunner, matches
from ranch_assistant.model import Catalog, Planner, Policy, Snapshot
@@ -144,63 +142,7 @@ class CoreTests(unittest.TestCase):
self.assertEqual(post.call_count, 1)
self.assertNotIn("private-token", str(raised.exception))
def test_budget_stamina_tickets_stale_and_persistent_daily_limit(self):
snapshot = self.snapshot()
config = FarmConfig(daily_limit=1)
with workspace_temp() as folder:
budget = FarmBudget(Path(folder) / "runs.json")
self.assertTrue(budget.check(snapshot, config, self.catalog)[0])
snapshot.raw["master"]["ti"] = 5
self.assertFalse(budget.check(snapshot, config, self.catalog)[0])
snapshot.raw["master"]["ti"] = 100
snapshot.raw["items"] = []
self.assertFalse(budget.check(snapshot, config, self.catalog)[0])
snapshot = self.snapshot()
snapshot.received_at -= 60
self.assertFalse(budget.check(snapshot, config, self.catalog)[0])
snapshot.received_at = time.time()
budget.reserve(snapshot, config)
restarted = FarmBudget(Path(folder) / "runs.json")
self.assertFalse(restarted.check(snapshot, config, self.catalog)[0])
def test_farm_screen_gate_and_real_tap_sequence(self):
with workspace_temp() as folder:
folder = Path(folder)
blank = Image.new("RGB", (200, 400), "black")
ready, victory = blank.copy(), blank.copy()
draw = ImageDraw.Draw(ready)
draw.rectangle((10, 10, 99, 39), fill="green")
draw.rectangle((20, 300, 99, 349), fill="red")
ImageDraw.Draw(victory).rectangle((100, 200, 179, 249), fill="blue")
boxes = {"stage": (10, 10, 100, 40), "entry": (20, 300, 100, 350), "victory": (100, 200, 180, 250)}
templates = {}
for name, box in boxes.items():
(victory if name == "victory" else ready).crop(box).save(folder / f"{name}.png")
templates[name] = {"screen": [200, 400], "box": box, "file": name + ".png", "stage_id": "bd00"}
class FakeAdb:
image = ready
taps = []
def foreground(self): return True
def screenshot(self): return self.image
def tap(self, x, y): self.taps.append((x, y))
adb = FakeAdb()
runner = FarmRunner(adb, self.catalog, folder)
runner.config = FarmConfig(templates=templates)
runner.start()
bad = ready.copy()
ImageDraw.Draw(bad).rectangle(boxes["stage"], fill="black")
adb.image = bad
runner.tick(self.snapshot())
self.assertEqual(adb.taps, [])
adb.image = ready
with patch("ranch_assistant.farming.time.monotonic", return_value=10): runner.tick(self.snapshot())
self.assertEqual(len(adb.taps), 1)
adb.image = victory
with patch("ranch_assistant.farming.time.monotonic", return_value=13): runner.tick(self.snapshot())
adb.image = ready
with patch("ranch_assistant.farming.time.monotonic", return_value=16): runner.tick(self.snapshot())
self.assertEqual(runner.completed, 1)
self.assertEqual(len(adb.taps), 2)
class WireIntegrationTests(unittest.TestCase):
@@ -242,7 +184,8 @@ class WireIntegrationTests(unittest.TestCase):
engine = Engine(catalog, client)
engine.policy = Policy(strategy="gold", protect_star=6, protect_quality=5, fill=False)
engine.poll()
self.assertFalse(any(p.endswith("stackCheckProcess") or p.endswith("monsterSell") for p, _ in calls))
self.assertTrue(any(p.endswith("stackCheckProcess") for p, _ in calls))
self.assertFalse(any(p.endswith("monsterSell") for p, _ in calls))
engine.auto = True
snapshot, _, _ = engine.poll()
self.assertEqual(sum(p.endswith("monsterSell") for p, _ in calls), 1)
+176
View File
@@ -0,0 +1,176 @@
import copy
from dataclasses import asdict
import json
import os
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.cultivation import CultivationSelector, growth_score
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, Planner, Policy, Snapshot
from ranch_assistant.policy_io import import_config, portable_config
from ranch_assistant.tests.test_core import workspace_temp
def monster(catalog, mid, *, level=10, feel=0, scale=.3, species=1001010, process=3):
row = catalog.monster(species)
return {"id": mid, "typeId": species, "process": process, "mode": 2, "level": level,
"feel": feel, "entangleLevel": 0, "giftTime": 0, "roomId": 1, "lock": 0,
**{"g" + stat.capitalize(): row[stat + "_grow_min"] + scale * (row[stat + "_grow_max"] - row[stat + "_grow_min"])
for stat in ("atk", "def", "hp", "dex")}}
class CultivationTests(unittest.TestCase):
def setUp(self):
self.catalog = Catalog()
self.snapshot = demo_snapshot(self.catalog)
self.snapshot.raw.update(monsters=[], teams=[], stacks=[])
def test_representative_prefers_level_then_feel_then_growth(self):
rows = [monster(self.catalog, 1, level=11, feel=0, scale=.1),
monster(self.catalog, 2, level=10, feel=99, scale=1),
monster(self.catalog, 3, level=11, feel=1, scale=.1),
monster(self.catalog, 4, level=11, feel=1, scale=.8),
monster(self.catalog, 5, level=99, feel=200, scale=1, process=2)]
self.snapshot.raw["monsters"] = rows
selector = CultivationSelector(self.catalog)
self.assertEqual(selector.select(self.snapshot)["1001010"]["id"], 4)
rows[1]["level"] = 12
self.assertEqual(selector.select(self.snapshot)["1001010"]["id"], 2)
def test_ties_are_chosen_once_persisted_and_do_not_leak_to_other_role(self):
self.snapshot.raw["monsters"] = [monster(self.catalog, 1), monster(self.catalog, 2)]
with workspace_temp() as folder:
path = folder / "choices.json"
with patch("ranch_assistant.cultivation.random.choice", side_effect=lambda choices: choices[-1]) as draw:
selector = CultivationSelector(self.catalog, path)
self.assertEqual(selector.select(self.snapshot)["1001010"]["id"], 2)
selector.select(self.snapshot)
self.assertEqual(draw.call_count, 1)
with patch("ranch_assistant.cultivation.random.choice", side_effect=AssertionError("Re-selected an exact tie")):
self.assertEqual(CultivationSelector(self.catalog, path).select(self.snapshot)["1001010"]["id"], 2)
self.snapshot.raw["master"]["id"] += 1
with patch("ranch_assistant.cultivation.random.choice", side_effect=lambda choices: choices[0]):
self.assertEqual(CultivationSelector(self.catalog, path).select(self.snapshot)["1001010"]["id"], 1)
def test_cached_selection_uses_current_cooldown_and_bond_cap(self):
self.snapshot.raw["monsters"] = [monster(self.catalog, 1)]
selector = CultivationSelector(self.catalog)
selector.select(self.snapshot)
updated = Snapshot(copy.deepcopy(self.snapshot.raw))
updated.raw["monsters"][0].update(giftTime=123456789, entangleLevel=2)
chosen = selector.select(updated)["1001010"]
self.assertIs(chosen, updated.raw["monsters"][0])
self.assertEqual((chosen["giftTime"], chosen["entangleLevel"]), (123456789, 2))
def test_better_growth_is_kept_independently_of_four_s_and_equal_or_worse_is_not(self):
representative = monster(self.catalog, 1, level=50, feel=90, scale=.3)
hatched = monster(self.catalog, 2, level=1, scale=.4, process=2)
self.snapshot.raw["monsters"] = [representative, hatched]
planner = Planner(self.catalog)
policy = Policy(strategy="gold", protect_star=6, protect_quality=6, keep_better_quality=True)
self.assertEqual(planner.disposition(hatched, self.snapshot, policy), "keep")
self.assertIn("同种培养代表 #1", planner.protection_reason(hatched, self.snapshot, policy))
policy.keep_better_quality = False
self.assertEqual(planner.disposition(hatched, self.snapshot, policy), "sell")
policy.keep_better_quality = True
for scale in (.3, .2):
self.snapshot.raw["monsters"][1] = monster(self.catalog, 2, scale=scale, process=2)
self.assertEqual(planner.disposition(self.snapshot.monsters[2], self.snapshot, policy), "sell")
def test_missing_species_or_unknown_reference_is_conservatively_retained(self):
hatched = monster(self.catalog, 2, process=2)
self.snapshot.raw["monsters"] = [hatched]
policy = Policy(protect_star=6, protect_quality=5, keep_better_quality=True)
planner = Planner(self.catalog)
self.assertIn("首次", planner.protection_reason(hatched, self.snapshot, policy))
reference = monster(self.catalog, 1, level=50)
reference["gAtk"] = None
self.snapshot.raw["monsters"].append(reference)
self.assertIn("尚未同步", planner.protection_reason(hatched, self.snapshot, policy))
def test_gifts_target_only_the_representative_and_do_not_move_to_duplicates_at_cap(self):
best = monster(self.catalog, 1, level=30)
duplicate = monster(self.catalog, 2, level=29, feel=50, scale=1)
self.snapshot.raw["monsters"] = [best, duplicate]
self.snapshot.raw["items"] = [{"id": 1, "typeId": 30005, "num": 20}]
policy = Policy(gift_enabled=True, gift_auto_representative=True, gift_liked_only=False,
gift_targets={"2": 1}, gift_items={"30005": {"enabled": True, "reserve": 2}})
planner = GiftPlanner(self.catalog)
self.assertEqual(planner.plan(self.snapshot, policy)[0].payload["monsterId"], 1)
best["feel"] = self.catalog.max_feel(best)
self.assertEqual(planner.plan(self.snapshot, policy), [])
best["feel"] = 0
best["giftTime"] = self.snapshot.now * 1000
self.assertEqual(planner.plan(self.snapshot, policy), [])
def test_cooldown_or_unavailable_food_skips_to_other_species_without_wasting_on_duplicates(self):
self.snapshot.raw["monsters"] = [monster(self.catalog, 1, level=50), monster(self.catalog, 2, level=40),
monster(self.catalog, 3, level=20, species=1002010)]
self.snapshot.raw["monsters"][0]["giftTime"] = self.snapshot.now * 1000
self.snapshot.raw["items"] = [{"id": 1, "typeId": 30005, "num": 3}]
policy = Policy(gift_enabled=True, gift_auto_representative=True, gift_liked_only=False,
gift_items={"30005": {"enabled": True, "reserve": 2}})
planner = GiftPlanner(self.catalog)
self.assertEqual(planner.plan(self.snapshot, policy)[0].payload["monsterId"], 3)
self.snapshot.raw["items"][0]["num"] = 2
self.assertEqual(planner.plan(self.snapshot, policy), [])
def test_auto_gift_representative_is_also_protected_from_hatch_disposal(self):
representative = monster(self.catalog, 1, level=20)
self.snapshot.raw["monsters"] = [representative, monster(self.catalog, 2, level=1)]
policy = Policy(strategy="gold", protect_star=6, protect_quality=5, gift_auto_representative=True)
planner = Planner(self.catalog)
self.assertTrue(planner.protected(representative, self.snapshot, policy))
self.assertFalse(planner.protected(self.snapshot.monsters[2], self.snapshot, policy))
def test_growth_score_normalizes_health_and_attack_to_their_own_ranges(self):
mon = monster(self.catalog, 1, scale=.5)
self.assertAlmostEqual(growth_score(self.catalog, mon), .5, places=3)
mon["gHp"] = self.catalog.monster(1001010)["hp_grow_max"]
self.assertAlmostEqual(growth_score(self.catalog, mon), .625, places=3)
class CultivationGuiTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.app = W.QApplication.instance() or W.QApplication([])
def wait(self, predicate):
for _ in range(800):
self.app.processEvents()
QTest.qWait(2)
if predicate():
return
self.fail("Cultivation preview did not finish")
def test_rule_flags_autosave_and_portable_settings_and_representative_preview(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.keep_better_quality.setChecked(True)
window.gift_auto_representative.setChecked(True)
self.wait(lambda: not window.auto_save_timer.isActive())
saved = json.loads((folder / "settings.json").read_text(encoding="utf-8"))
self.assertTrue(saved["policy"]["keep_better_quality"])
self.assertTrue(window.engine.policy.gift_auto_representative)
imported = import_config(portable_config(window.config_value(), window.engine.snapshot), window.engine.snapshot)
self.assertTrue(imported["policy"]["keep_better_quality"])
self.assertTrue(imported["policy"]["gift_auto_representative"])
window.engine.plans()
window.tabs.setCurrentWidget(window.gift_page)
self.assertGreater(window.gift_representatives.rowCount(), 0)
self.assertFalse(window.strategy_toggle.isChecked())
window.load_config()
self.assertTrue(window.keep_better_quality.isChecked())
self.assertTrue(window.gift_auto_representative.isChecked())
finally:
window.close()
@@ -0,0 +1,256 @@
import copy
import json
import os
import sqlite3
from types import SimpleNamespace
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.drop_statistics import SweepStatistics, analyze, normalize_reward, reward_text
from ranch_assistant.engine import Engine
from ranch_assistant.gui import Window
from ranch_assistant.statistics_gui import StatisticsPage
from ranch_assistant.model import Catalog
from ranch_assistant.sweeping import SweepPolicy, SweepRunner
from ranch_assistant.tests.test_activities import scenario, FakeClient
from ranch_assistant.tests.test_core import workspace_temp
REWARD = {"money": 32, "exp": 64, "ke": 0, "ti": 0, "items": [
{"id": 100, "typeId": 30005, "num": 2}, {"id": 100, "typeId": 30005, "num": 3},
{"id": 101, "typeId": 1001010, "num": 1}], "monsters": []}
class DropStatisticsTests(unittest.TestCase):
def setUp(self):
self.catalog = Catalog()
def test_quantity_is_aggregated_but_presence_is_counted_once_per_sample(self):
store = SweepStatistics(self.catalog)
store.record(1, "0101", "3", "sweep", "one", 1000, REWARD)
store.record(1, "0101", "3", "sweep", "two", 1001, {"money": 32, "items": []})
totals, rows = analyze(self.catalog, store.snapshot(1), "0101", "3")
item = next(row for row in rows if row["key"] == "item:30005")
self.assertEqual((item["hits"], item["units"], item["samples"], item["rate"], item["average"]), (1, 5, 2, .5, 2.5))
self.assertEqual(totals["money"], 64)
self.assertLessEqual(item["interval"][0], .5)
self.assertGreaterEqual(item["interval"][1], .5)
self.assertIn("×5", reward_text(normalize_reward(self.catalog, REWARD)))
def test_items_per_stamina_uses_known_cost_totals_and_ignores_unknown_samples(self):
store = SweepStatistics(self.catalog)
store.record(1, "0101", "3", "sweep", "one", 1, {"items": [{"typeId": 30005, "num": 5}]}, spent=10)
store.record(1, "0101", "3", "sweep", "two", 2, {"items": [{"typeId": 30005, "num": 2}]}, spent=20)
store.record(1, "0101", "3", "sweep", "unknown", 3, {"items": [{"typeId": 30005, "num": 7}]})
total, rows = analyze(self.catalog, store.snapshot(1), "0101", "3")
row = next(row for row in rows if row["key"] == "item:30005")
self.assertEqual((total["known"], total["spent"], total["n"]), (2, 30, 3))
self.assertEqual((row["units"], row["cost_units"]), (14, 7))
self.assertAlmostEqual(row["per_stamina"], 7 / 30)
self.assertIsNone(next(row for row in analyze(self.catalog, store.snapshot(1), "0102", "1")[1])["per_stamina"])
def test_zero_stamina_and_refunds_do_not_create_infinite_or_net_cost_efficiency(self):
store = SweepStatistics(self.catalog)
store.record(1, "0101", "3", "event", "free", 1, {"items": [{"typeId": 30005, "num": 2}]}, spent=0)
total, rows = analyze(self.catalog, store.snapshot(1), "0101", "3", "event")
self.assertEqual(total["known"], 1)
self.assertTrue(all(row["per_stamina"] is None for row in rows))
store.record(1, "0101", "1", "event", "refund", 2, {"ti": 5, "items": [{"typeId": 30005, "num": 2}]}, spent=5)
total, rows = analyze(self.catalog, store.snapshot(1), "0101", "1", "event")
self.assertEqual((total["spent"], total["ti"]), (5, 5))
self.assertEqual(next(r for r in rows if r["key"] == "item:30005")["per_stamina"], .4)
def test_earlier_database_without_known_cost_columns_keeps_rewards_and_migrates(self):
with workspace_temp() as folder:
path = folder / "old.sqlite3"
db = sqlite3.connect(path)
try:
db.executescript("""CREATE TABLE totals(owner TEXT,stage TEXT,level TEXT,kind TEXT,n INTEGER,money INTEGER,exp INTEGER,ke INTEGER,ti INTEGER,spent INTEGER,PRIMARY KEY(owner,stage,level,kind));
CREATE TABLE drops(owner TEXT,stage TEXT,level TEXT,kind TEXT,key TEXT,typeId TEXT,category TEXT,name TEXT,hits INTEGER,units INTEGER,PRIMARY KEY(owner,stage,level,kind,key));
INSERT INTO totals VALUES('1','0101','3','sweep',1,32,64,0,0,16);
INSERT INTO drops VALUES('1','0101','3','sweep','item:30005','30005','item','sample',1,2);""")
db.commit()
finally:
db.close()
store = SweepStatistics(self.catalog, path)
total, rows = analyze(self.catalog, store.snapshot(1), "0101", "3")
self.assertEqual((total["n"], total["known"], total["spent"]), (1, 0, 0))
self.assertEqual(next(r for r in rows if r["key"] == "item:30005")["units"], 2)
store.record(1, "0101", "3", "sweep", "new", 2, {"items": [{"typeId": 30005, "num": 3}]}, spent=10)
self.assertEqual(next(r for r in analyze(self.catalog, store.snapshot(1), "0101", "3")[1] if r["key"] == "item:30005")["per_stamina"], .3)
def test_role_difficulty_source_and_repeated_response_are_isolated_after_restart(self):
with workspace_temp() as folder:
path = folder / "rewards.sqlite3"
store = SweepStatistics(self.catalog, path)
self.assertTrue(store.record(1, "0101", "3", "sweep", "same", 1, REWARD))
self.assertFalse(store.record(1, "0101", "3", "sweep", "same", 1, REWARD))
store.record(1, "0101", "1", "sweep", "difficulty", 2, REWARD)
store.record(1, "0101", "3", "event", "event", 3, {"items": []})
store.record(2, "0101", "3", "sweep", "same", 4, REWARD)
restored = SweepStatistics(self.catalog, path)
totals, rows = analyze(self.catalog, restored.snapshot(1), "0101", "3", "all")
self.assertEqual(totals["n"], 2)
self.assertEqual(next(r for r in rows if r["key"] == "item:30005")["rate"], .5)
self.assertEqual(analyze(self.catalog, restored.snapshot(2), "0101", "3")[0]["n"], 1)
def test_no_samples_and_unobserved_static_drop_are_distinguished(self):
store = SweepStatistics(self.catalog)
_, rows = analyze(self.catalog, store.snapshot(1), "0101", "3")
self.assertTrue(rows)
self.assertTrue(all(row["rate"] is None for row in rows))
store.record(1, "0101", "3", "sweep", "one", 1, {"items": [{"typeId": 99999999, "num": 1}]})
_, rows = analyze(self.catalog, store.snapshot(1), "0101", "3")
self.assertTrue(all(row["rate"] == 0 for row in rows if row["configured"]))
unknown = next(row for row in rows if row["key"] == "item:99999999")
self.assertFalse(unknown["configured"])
self.assertEqual(unknown["rate"], 1)
def test_malformed_or_missing_reward_does_not_add_a_sample(self):
store = SweepStatistics(self.catalog)
for reward in (None, {"items": [{"typeId": 30005, "num": None}]}, {"items": [{"typeId": 30005, "num": -1}]}):
with self.assertRaises((ValueError, TypeError)):
store.record(1, "0101", "3", "sweep", "bad", 1, reward)
self.assertEqual(store.snapshot(1)["totals"], {})
def test_log_backfill_matches_role_and_deduplicates_live_and_rotated_records(self):
with workspace_temp() as folder:
path = folder / "network_debug.jsonl"
battle = {"win": True, "leftTime": 0, "killNum": 0, "totalDamage": 0, "cheatNum": 0,
"battlePosition": {"battleType": "stage", "stageId": "0101", "stageLevel": "3"}}
entries = [{"operation": "读取角色", "kind": "response", "body": {"master": {"id": 1}}},
{"operation": "battleService/battleEnd", "kind": "request", "request_id": "normal", "body": {"battleData": battle}},
{"operation": "battleService/battleEnd", "kind": "response", "request_id": "normal", "http_status": 200,
"time": "2026-11-08T12:00:00+08:00", "body": {"resCode": 0, "reward": REWARD}},
{"operation": "stageService/stageStart", "kind": "request", "request_id": "event", "body": {"stageTypeId": "0101", "stageLevel": "3"}},
{"operation": "stageService/stageStart", "kind": "response", "request_id": "event", "http_status": 200,
"time": "2026-11-08T12:00:01+08:00", "body": {"resCode": 0, "triggerEvent": True,
"stageEvent": {"hideStageId": None, "result": {"items": []}}}}]
text = "\n".join(json.dumps(row) for row in entries)
path.write_text(text, encoding="utf-8")
path.with_name("network_debug.previous.jsonl").write_text(text, encoding="utf-8")
store = SweepStatistics(self.catalog, folder / "stats.sqlite3")
store.record(1, "0101", "3", "sweep", "request:normal", 1, REWARD)
store.import_log(1, path)
self.assertEqual(analyze(self.catalog, store.snapshot(1), "0101", "3", "all")[0]["n"], 2)
store.import_log(2, path)
self.assertEqual(store.snapshot(2)["totals"], {})
restored = SweepStatistics(self.catalog, folder / "stats.sqlite3")
restored.import_log(1, path)
self.assertEqual(analyze(self.catalog, restored.snapshot(1), "0101", "3", "all")[0]["n"], 2)
def test_confirmed_reward_is_saved_before_later_record_request_failure(self):
catalog, snapshot = scenario()
runner = SweepRunner(catalog)
client = FakeClient(snapshot)
client.fail = "battleService/recordBattleResult"
stage = runner.next(snapshot, SweepPolicy(True, {"0101": {"enabled": True, "level": "3", "limit": 3}}))
with self.assertRaises(TimeoutError):
runner.run(client, snapshot, stage, SweepPolicy(True, {"0101": {"enabled": True, "level": "3", "limit": 3}}))
self.assertEqual(runner.statistics.snapshot(snapshot.raw["master"]["id"])["totals"]["0101:3:sweep"]["n"], 1)
self.assertIsNone(runner.state["pending"])
def test_local_statistics_failure_does_not_repeat_or_interrupt_sweep_settlement(self):
catalog, snapshot = scenario()
runner = SweepRunner(catalog)
client = FakeClient(snapshot)
policy = SweepPolicy(True, {"0101": {"enabled": True, "level": "3", "limit": 3}})
with patch.object(runner.statistics, "record", side_effect=OSError("synthetic failure")):
runner.run(client, snapshot, runner.next(snapshot, policy), policy)
self.assertIsNone(runner.state["pending"])
self.assertEqual(len(client.calls), 3)
self.assertIn("未写入", runner.statistics_error)
def test_engine_reports_normal_sweep_rewards(self):
catalog, snapshot = scenario()
client = FakeClient(snapshot)
engine = Engine(catalog, client)
engine.policy.enabled = False
engine.sweep_policy = SweepPolicy(True, {"0101": {"enabled": True, "level": "3", "limit": 3}})
engine.auto = True
_, _, message = engine.poll()
self.assertIn("扫荡完成", message)
self.assertIn("金币 1", message)
class AnalysisGuiTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.app = W.QApplication.instance() or W.QApplication([])
def wait(self, predicate):
for _ in range(1000):
self.app.processEvents()
QTest.qWait(2)
if predicate():
return
self.fail("Analysis rendering did not finish")
def test_static_stage_selection_table_chart_and_source_filter(self):
catalog, snapshot = scenario()
store = SweepStatistics(catalog)
store.record(1, "0101", "3", "sweep", "one", 1, REWARD, spent=10)
store.record(1, "0101", "3", "sweep", "two", 2, {"items": []}, spent=10)
store.record(1, "0101", "3", "event", "three", 3, {"items": []})
page = StatisticsPage(catalog)
try:
page.set_data(catalog, store.snapshot(1))
self.wait(lambda: not page.row_batch.running)
self.assertEqual(page.current_key, ("0101", "3"))
self.assertIn("2 个已确认样本", page.summary.text())
self.assertTrue(page.chart_view.chart().series())
row = next(i for i in range(page.table.rowCount()) if page.table.item(i, 0).text() == catalog.data["item_names"]["30005"])
self.assertEqual(page.table.item(row, 5).text(), "50.00%")
self.assertEqual(page.table.item(row, 7).text(), "0.25")
page.chart_metric.setCurrentIndex(page.chart_metric.findData("per_stamina"))
self.assertEqual(page.chart_view.chart().title(), "每点体力数量")
page.source.setCurrentIndex(page.source.findData("event"))
self.assertIn("1 个已确认样本", page.summary.text())
page.tree.setCurrentItem(page.level_items["0102", "1"])
self.assertIn("尚无此范围的样本", page.summary.text())
self.assertTrue(all(page.table.item(i, 5).text() == "—" for i in range(page.table.rowCount())))
finally:
page.row_batch.stop()
page.close()
def test_analysis_tab_is_next_to_sweeping_and_refresh_is_local_only(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)
labels = [window.tabs.tabText(i) for i in range(window.tabs.count())]
self.assertEqual(labels[labels.index("自动扫荡") + 1], "数据分析")
window.tabs.setCurrentWidget(window.analysis_page)
self.wait(lambda: not window.analysis_page.row_batch.running)
with patch.object(window.engine, "poll", side_effect=AssertionError("Analysis must not refresh game state")):
owner = window.engine.snapshot.raw["master"]["id"]
window.engine.sweeper.statistics.record(owner, "0101", "3", "sweep", "local-refresh", 1, REWARD, spent=16)
window.refresh_page(window.analysis_page)
self.wait(lambda: not window.busy)
window.tabs.setCurrentWidget(window.slot_page)
window.tabs.setCurrentWidget(window.analysis_page)
self.assertEqual(window.analysis_page.data["totals"]["0101:3:sweep"]["n"], 1)
self.assertIn("本地", window.log.toPlainText())
finally:
window.close()
def test_paused_large_stage_tree_resumes_when_new_statistics_arrive(self):
catalog = Catalog()
store = SweepStatistics(catalog)
page = StatisticsPage(catalog)
try:
page.set_data(catalog, store.snapshot(1))
page.row_batch.stop()
store.record(1, "0101", "3", "sweep", "one", 1, REWARD, spent=16)
page.set_data(catalog, store.snapshot(1))
self.wait(lambda: not page.row_batch.running)
self.assertEqual(len(page.level_items), sum(len(stage.get("level", {})) for stage in catalog.data["stage_info"].values()))
self.assertEqual(page.current_key, ("0101", "3"))
finally:
page.row_batch.stop()
page.close()
-64
View File
@@ -8,13 +8,10 @@ import unittest
from urllib.parse import parse_qs, urlsplit
from unittest.mock import patch
from PIL import Image, ImageDraw
from ranch_assistant.api import ApiError, Client, DEFAULT_KEY, Session, decode, encode, server_entries, server_id
from ranch_assistant.capture import load_buttons, save_page, saved_profiles, write_buttons
from ranch_assistant.engine import Engine, demo_snapshot
from ranch_assistant.debug import TraceLog
from ranch_assistant.farming import FarmConfig, FarmRunner
from ranch_assistant.login import PasswordLogin, SDK_APP_ID, SDK_APP_SECRET, server_labels
from ranch_assistant.maps import stages
from ranch_assistant.model import Catalog, Policy
@@ -230,67 +227,6 @@ class PlanningTests(unittest.TestCase):
self.assertEqual((first.stamina, second.stamina), (7, 8))
class CaptureTests(unittest.TestCase):
def test_profile_scope_button_binding_and_changed_capture(self):
with workspace_temp() as folder:
ready = Image.new("RGB", (100, 200), "blue")
victory = Image.new("RGB", (100, 200), "green")
path, _ = save_page(folder, ready, "phone-a", "bd00", "1", "stage_ready")
save_page(folder, victory, "phone-a", "bd00", "1", "victory")
alternate, _ = save_page(folder, ready.resize((200, 400)), "phone-a", "bd00", "1", "stage_ready")
other, _ = save_page(folder, ready, "phone-b", "bd00", "1", "stage_ready")
self.assertEqual(len({path, alternate, other}), 3)
self.assertEqual(len(saved_profiles(folder, "bd00", "1", "phone-a")), 2)
regions = {"stage": {"box": [0, 0, 20, 20]}, "entry": {"box": [20, 20, 40, 40]},
"victory": {"box": [40, 40, 60, 60], "tap": [70, 180]}}
write_buttons(path, folder, regions)
templates = load_buttons(path, folder, "bd00", "1", "phone-a")
self.assertEqual(templates["victory"]["tap"], [70, 180])
with self.assertRaises(ValueError):
load_buttons(path, folder, "bd00", "2")
with self.assertRaises(ValueError):
load_buttons(path, folder, "bd00", "1", "phone-b")
save_page(folder, Image.new("RGB", ready.size, "red"), "phone-a", "bd00", "1", "stage_ready")
with self.assertRaises(ValueError):
load_buttons(path, folder, "bd00", "1")
def test_runtime_device_resolution_and_separate_victory_tap(self):
with workspace_temp() as folder:
ready = Image.new("RGB", (100, 200), "black")
victory = ready.copy()
ImageDraw.Draw(ready).rectangle((0, 0, 40, 40), fill="blue")
ImageDraw.Draw(victory).rectangle((40, 40, 60, 60), fill="green")
path, _ = save_page(folder, ready, "phone-a", "bd00", "1", "stage_ready")
save_page(folder, victory, "phone-a", "bd00", "1", "victory")
write_buttons(path, folder, {"stage": {"box": [0, 0, 20, 20]}, "entry": {"box": [20, 20, 40, 40]},
"victory": {"box": [40, 40, 60, 60], "tap": [70, 180]}})
class FakeAdb:
serial = "phone-a"
image = ready
taps = []
def foreground(self): return True
def screenshot(self): return self.image
def tap(self, x, y): self.taps.append((x, y))
adb = FakeAdb()
catalog = Catalog()
runner = FarmRunner(adb, catalog, folder)
runner.config = FarmConfig(capture_profile=str(path.relative_to(folder)))
runner.start()
with patch("ranch_assistant.farming.time.monotonic", return_value=10):
runner.tick(demo_snapshot(catalog))
adb.image = victory
with patch("ranch_assistant.farming.time.monotonic", return_value=13):
runner.tick(demo_snapshot(catalog))
self.assertEqual(adb.taps[-1], (70, 180))
adb.serial = "phone-b"
with self.assertRaises(RuntimeError):
runner.tick(demo_snapshot(catalog))
adb.serial = "phone-a"
runner.start()
adb.image = ready.resize((200, 400))
with self.assertRaises(RuntimeError):
runner.tick(demo_snapshot(catalog))
self.assertEqual(len(adb.taps), 2)
if __name__ == "__main__":
+9 -9
View File
@@ -150,17 +150,16 @@ class GrowthTests(unittest.TestCase):
self.assertEqual(sum(name == "growth" for name, _ in client.calls), 1)
self.assertFalse(any(name == "monsterService/monsterSell" for name, _ in client.calls))
def test_monitor_is_read_only_and_explicit_sync_does_not_dispatch(self):
def test_monitor_automatically_syncs_growth_without_dispatch(self):
client = GrowthClient(self.catalog, age=610)
engine = self.engine(client)
engine.auto = False
snapshot, _, message = engine.poll()
self.assertFalse(any(name == "growth" for name, _ in client.calls))
self.assertIn("仅监控", message)
snapshot, plans, _ = engine.sync_growth()
self.assertTrue(any(name == "growth" for name, _ in client.calls))
self.assertIn("成长结算", message)
self.assertEqual(snapshot.monsters[501]["mode"], 2)
self.assertEqual(self.catalog.quality_text(snapshot.monsters[501]), "C/C/C/C")
self.assertTrue(any(action.kind == "sell" for action in plans))
self.assertTrue(any(action.kind == "sell" for action in engine.plans()))
self.assertFalse(any(name == "monsterService/monsterSell" for name, _ in client.calls))
def test_mature_protected_monster_with_null_room_id_can_be_collected(self):
@@ -203,8 +202,9 @@ class GrowthGuiTests(unittest.TestCase):
row = next(i for i in range(window.slots.rowCount()) if window.slots.item(i, 1).text() == "1")
self.assertIn("待同步", window.slots.item(row, 5).text())
self.assertIn("待成熟", window.slots.item(row, 7).text())
self.assertNotEqual(window.monsters.item(0, 4).text(), "C/C/C/C")
window.sync_growth_button.click()
self.assertNotEqual(window.monsters.monster_items[501].text(4), "C/C/C/C")
window.engine.last_heartbeat = __import__("time").monotonic()
window.schedule()
for _ in range(200):
self.app.processEvents()
QTest.qWait(5)
@@ -213,8 +213,8 @@ class GrowthGuiTests(unittest.TestCase):
row = next(i for i in range(window.slots.rowCount()) if window.slots.item(i, 1).text() == "1")
self.assertEqual(window.slots.item(row, 7).text(), "S/S/S/S")
self.assertIn("资质", window.slots.item(row, 8).text())
self.assertIn("S/S/S/S", window.monsters.item(0, 4).text())
self.assertFalse(window.execute.isChecked())
self.assertIn("S/S/S/S", window.monsters.monster_items[501].text(4))
self.assertFalse(window.strategy_toggle.isChecked())
self.assertFalse(any(name == "monsterService/monsterSell" for name, _ in client.calls))
finally:
window.close()
+16 -55
View File
@@ -5,7 +5,7 @@ import json
import unittest
from unittest.mock import patch
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QApplication
from PySide6.QtWidgets import QApplication, QPushButton, QCheckBox
from ranch_assistant import gui
from ranch_assistant.tests.test_core import workspace_temp
@@ -29,20 +29,32 @@ class GuiTests(unittest.TestCase):
window.timer.stop()
try:
self.wait(window)
self.assertIn("页面截图配置", [window.tabs.tabText(i) for i in range(window.tabs.count())])
labels = [window.tabs.tabText(i) for i in range(window.tabs.count())]
self.assertNotIn("页面截图配置", labels)
self.assertNotIn("体力刷图", labels)
self.assertIn("自动扫荡", labels)
self.assertNotIn("地图关卡", labels)
self.assertEqual(labels[-1], "收益资料")
self.assertLess(labels.index("自动孵蛋"), labels.index("自动扫荡"))
self.assertEqual(window.yields.rowCount(), 749)
self.assertEqual(window.styleSheet(), "")
buttons = {button.text() for button in window.findChildren(QPushButton)}
self.assertIn("开启策略", buttons)
for removed in ("开始监控", "停止监控", "仅监控", "开始执行勾选功能", "停止执行",
"开始执行勾选策略", "开始扫荡", "停止扫荡", "开始每日事务", "停止每日事务"):
self.assertNotIn(removed, buttons)
self.assertNotIn("自动执行已启用策略", {check.text() for check in window.findChildren(QCheckBox)})
window.strategy.setCurrentIndex(window.strategy.findData("gold"))
window.egg_rules = {str(m["typeId"]): {"enabled": True, "action": "sell"} for m in window.engine.snapshot.raw["monsters"][:2]}
window.protect_star.setValue(6)
window.protect_quality.setCurrentIndex(window.protect_quality.findData(5))
window.fill.setChecked(False)
window.execute.setChecked(True)
window.set_strategy_checked(True)
before = len(window.engine.snapshot.raw["monsters"])
window.refresh()
self.wait(window)
self.assertEqual(len(window.engine.snapshot.raw["monsters"]), before)
window.start_monitor.setChecked(True)
window.monitoring = True
window.refresh(automated=True)
self.wait(window)
self.assertEqual(len(window.engine.snapshot.raw["monsters"]), before - 1)
@@ -58,57 +70,6 @@ class GuiTests(unittest.TestCase):
finally:
window.close()
def test_page_buttons_only_capture_and_restore_profile(self):
from PIL import Image
from ranch_assistant.capture import PAGES
operations = []
class FakeAdb:
def __init__(self, executable="", serial=""):
self.serial = serial
def foreground(self):
operations.append("foreground")
return True
def run(self, *args):
operations.append(args)
if args != ("get-serialno",):
raise AssertionError("Screenshot flow attempted another ADB command")
return "test-phone"
def screenshot(self):
operations.append("screenshot")
return Image.new("RGB", (320, 640), "green")
def tap(self, *args):
raise AssertionError("Screenshot flow must never tap")
with workspace_temp() as folder, patch.object(gui, "STATE", folder):
window = gui.Window()
window.timer.stop()
try:
self.wait(window)
window.start_monitor.setChecked(True)
with patch.object(gui, "Adb", FakeAdb):
for index in range(len(PAGES)):
window.capture_rows.cellWidget(index, 2).click()
self.wait(window)
self.assertFalse(window.monitoring)
profile = json.loads(window.capture_profile.read_text(encoding="utf-8"))
self.assertEqual(set(profile["captures"]), {p[0] for p in PAGES})
self.assertEqual(operations.count("screenshot"), len(PAGES))
self.assertFalse(window.capture_preview.selectable)
original = window.capture_profile
window.stage.setCurrentIndex(1)
self.assertIsNone(window.capture_profile)
window.stage.setCurrentIndex(0)
self.assertEqual(window.capture_profile, original)
finally:
window.close()
restored = gui.Window()
restored.timer.stop()
try:
self.wait(restored)
self.assertEqual(restored.capture_profile, original)
restored.preview_capture(0, 0)
self.assertEqual(restored.capture_preview.image.size, (320, 640))
finally:
restored.close()
def test_password_result_accepts_serverId_and_handles_missing_identifier(self):
from unittest.mock import Mock
+161
View File
@@ -0,0 +1,161 @@
import copy
from dataclasses import asdict
import os
import time
import unittest
from unittest.mock import patch
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6 import QtWidgets as W
from PySide6.QtTest import QTest
from ranch_assistant.api import Session
from ranch_assistant.engine import Engine, demo_snapshot
from ranch_assistant.gui import Window
from ranch_assistant.model import Catalog, EggRule, Policy, Snapshot
from ranch_assistant.tests.test_core import workspace_temp
class HatchClient:
def __init__(self, catalog):
self.value = copy.deepcopy(demo_snapshot(catalog).raw)
self.template = self.value["monsters"][0] | {"mode": 2}
self.value["monsters"] = []
self.value["stacks"] = [{"id": 1, "position": 0, "monsterId": -1},
{"id": 2, "position": 1, "monsterId": -1}, {"id": 4, "position": 3, "monsterId": -1}]
self.value["items"] = [{"id": 501, "typeId": self.template["typeId"], "num": 5}]
self.calls = []
self.session = Session("http://127.0.0.1/", "synthetic-test-token")
self.stale = False
def snapshot(self):
return Snapshot(copy.deepcopy(self.value))
def call(self, path, payload):
self.calls.append((path, payload))
if self.stale:
return {}
if path != "stackService/stackAddMonster":
raise AssertionError("Fast hatching executed another action")
egg = payload["eggs"][0]
mid = 1000 + len(self.calls)
next(slot for slot in self.value["stacks"] if slot["id"] == egg["stackId"])["monsterId"] = mid
next(item for item in self.value["items"] if item["id"] == egg["itemId"])["num"] -= 1
self.value["monsters"].append(self.template | {"id": mid, "mode": 0, "timeStart": int(time.time() * 1000)})
return {}
def persist_session(self):
pass
def close(self):
pass
def policy_for(client):
return Policy(manual_eggs=True, protect_star=6, protect_quality=5, buy=True,
egg_rules={str(client.template["typeId"]): asdict(EggRule(enabled=True, action="sell"))})
class HatchTimingTests(unittest.TestCase):
def test_fast_hatching_skips_other_actions_and_retains_vip_and_reserve_limits(self):
catalog = Catalog()
client = HatchClient(catalog)
client.value["monsters"].append(client.template)
client.value["stacks"][0]["monsterId"] = client.template["id"]
engine = Engine(catalog, client)
engine.policy = policy_for(client)
engine.policy.reserved_eggs = {str(client.template["typeId"]): 4}
engine.auto = True
engine.read_snapshot()
self.assertEqual(engine.plans()[0].kind, "sell")
snapshot, _, _ = engine.poll(hatch_only=True)
self.assertEqual([path for path, _ in client.calls], ["stackService/stackAddMonster"])
self.assertEqual(client.calls[0][1]["eggs"][0]["stackId"], 2)
self.assertIn(client.template["id"], snapshot.monsters)
self.assertFalse(engine.pending_hatches)
self.assertEqual(client.value["stacks"][2]["monsterId"], -1)
def test_fast_worker_rechecks_stock_and_never_falls_back_to_buying(self):
catalog = Catalog()
client = HatchClient(catalog)
engine = Engine(catalog, client)
engine.policy = policy_for(client)
engine.auto = True
engine.poll(defer_hatch=True)
self.assertEqual(client.calls, [])
self.assertTrue(engine.pending_hatches)
client.value["items"][0]["num"] = 0
client.value["monsters"].append(client.template | {"mode": 0, "timeStart": 1})
engine.poll(hatch_only=True)
self.assertEqual(client.calls, [])
self.assertFalse(engine.pending_hatches)
def test_unconfirmed_hatch_stops_automation_before_another_fill(self):
catalog = Catalog()
client = HatchClient(catalog)
client.stale = True
engine = Engine(catalog, client)
engine.policy = policy_for(client)
engine.auto = True
with self.assertRaisesRegex(ValueError, "坑位状态尚未同步"):
engine.poll(hatch_only=True)
self.assertFalse(engine.auto)
engine.poll(hatch_only=True)
self.assertEqual(len(client.calls), 1)
class HatchTimerGuiTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.app = W.QApplication.instance() or W.QApplication([])
def wait(self, window):
for _ in range(500):
self.app.processEvents()
QTest.qWait(2)
if not window.busy:
return
self.fail("Background hatch did not finish")
def test_short_hatch_timer_does_not_change_poll_deadline_and_stops_on_pause(self):
with workspace_temp() as folder:
window = Window(folder)
window.timer.stop()
try:
self.wait(window)
client = HatchClient(window.catalog)
window.engine = Engine(window.catalog, client)
window.engine.last_heartbeat = time.monotonic()
window.egg_rules = policy_for(client).egg_rules
window.monitoring = True
window.set_strategy_checked(True)
with patch.object(window, "poll_delay", return_value=300), patch("ranch_assistant.gui.random.uniform", return_value=1.5) as draw:
window.refresh(automated=True)
self.wait(window)
deadline = window.next_poll
self.assertEqual(client.calls, [])
self.assertTrue(window.hatch_timer.isActive())
self.assertEqual(window.hatch_timer.interval(), 1500)
self.assertEqual(draw.call_args.args, (1, 2))
hatch_deadline = window.next_hatch
window.refresh(automated=True)
self.wait(window)
self.assertEqual(window.next_hatch, hatch_deadline)
self.assertEqual(draw.call_count, 1)
deadline = window.next_poll
window.next_hatch = time.monotonic() - 1
window.schedule()
self.wait(window)
self.assertEqual(len(client.calls), 1)
self.assertEqual(window.next_poll, deadline)
self.assertTrue(window.hatch_timer.isActive())
window.stop_workflow()
self.assertFalse(window.hatch_timer.isActive())
window.schedule()
self.assertEqual(len(client.calls), 1)
finally:
window.close()
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,91 @@
import copy
import os
import unittest
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6 import QtCore as C, QtWidgets as W
from PySide6.QtTest import QTest
from ranch_assistant.engine import demo_snapshot
from ranch_assistant.inventory_gui import InventoryTable
from ranch_assistant.model import Catalog
class InventoryRefreshTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.app = W.QApplication.instance() or W.QApplication([])
def drain(self, table):
for _ in range(200):
if not table.row_batch.running:
return
QTest.qWait(2)
self.fail("Inventory refresh did not finish")
def test_changed_inventory_reuses_cells_without_ownership_warnings(self):
catalog = Catalog()
snapshot = demo_snapshot(catalog)
table = InventoryTable(catalog)
messages = []
previous = C.qInstallMessageHandler(lambda kind, context, message: messages.append(message))
try:
table.set_data(snapshot, {})
self.drain(table)
table.sortItems(1, C.Qt.SortOrder.DescendingOrder)
cells = [table.item(row, 4) for row in range(table.rowCount())]
changed = copy.deepcopy(snapshot)
for item in changed.raw["items"]:
item["num"] += 7
table.set_data(changed, {})
self.drain(table)
counts = {str(item["typeId"]): item["num"] for item in changed.raw["items"]}
for row in range(table.rowCount()):
key = table.item(row, 0).data(C.Qt.ItemDataRole.UserRole)
self.assertEqual(table.item(row, 4).data(C.Qt.ItemDataRole.DisplayRole), counts[key])
self.assertIn(table.item(row, 4), cells)
self.assertEqual([message for message in messages if "already owned" in message], [])
finally:
C.qInstallMessageHandler(previous)
table.row_batch.stop()
table.close()
def test_two_accounts_filter_and_restart_partial_refresh(self):
catalog = Catalog()
snapshot = demo_snapshot(catalog)
keys = list(catalog.monsters)[:100]
snapshot.raw["items"] = [{"id": 1000 + i, "typeId": int(key), "num": i + 1}
for i, key in enumerate(keys)]
tables = [InventoryTable(catalog), InventoryTable(catalog)]
messages = []
previous = C.qInstallMessageHandler(lambda kind, context, message: messages.append(message))
try:
for table in tables:
table.set_data(snapshot, {})
table.set_filter(catalog.item_name(keys[-1]), 6)
table.set_data(snapshot, {})
self.drain(table)
self.assertGreater(table.rowCount(), 0)
table.set_filter()
table.set_data(snapshot, {})
self.drain(table)
table.sortItems(4, C.Qt.SortOrder.DescendingOrder)
changed = copy.deepcopy(snapshot)
changed.raw["items"].reverse()
table.set_data(changed, {})
self.drain(table)
self.assertEqual(table.rowCount(), 100)
for row in range(table.rowCount()):
key = table.item(row, 0).data(C.Qt.ItemDataRole.UserRole)
self.assertEqual(table.cellWidget(row, 6).property("item_type"), key)
self.assertIsNot(tables[0].item(0, 0), tables[1].item(0, 0))
self.assertEqual([message for message in messages if "already owned" in message], [])
finally:
C.qInstallMessageHandler(previous)
for table in tables:
table.row_batch.stop()
table.close()
if __name__ == "__main__":
unittest.main()
+97
View File
@@ -0,0 +1,97 @@
import json
import os
from dataclasses import asdict
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
from ranch_assistant.api import Session
from ranch_assistant.gui import Window
from ranch_assistant.stage_cache import StageCache
from ranch_assistant.tests.test_activities import scenario, FakeClient
from ranch_assistant.tests.test_core import workspace_temp
class MapCacheTests(unittest.TestCase):
def test_snapshot_changes_and_restart_reuse_cache_until_explicit_refresh(self):
catalog, snapshot = scenario()
with workspace_temp() as folder:
cache = StageCache(catalog, folder / "maps.json")
original = cache.get(snapshot)
original_json = (folder / "maps.json").read_text(encoding="utf-8")
snapshot.raw["history"]["unlockStage"]["0102"] = ["1", "2", "3"]
with patch("ranch_assistant.stage_cache.stages", side_effect=AssertionError("Unrequested refresh")):
self.assertIs(cache.get(snapshot), original)
restored = StageCache(catalog, folder / "maps.json")
self.assertEqual([asdict(row) for row in restored.get(snapshot)], [asdict(row) for row in original])
self.assertEqual((folder / "maps.json").read_text(encoding="utf-8"), original_json)
refreshed = cache.get(snapshot, refresh=True)
self.assertTrue(next(row for row in refreshed if row.stage_id == "0102" and row.level == "2").unlocked)
def test_cache_rejects_other_role_and_recovers_corrupt_local_file(self):
catalog, snapshot = scenario()
with workspace_temp() as folder:
path = folder / "maps.json"
cache = StageCache(catalog, path)
cache.get(snapshot)
snapshot.raw["master"]["id"] += 1
with patch("ranch_assistant.stage_cache.stages", wraps=__import__("ranch_assistant.maps", fromlist=["stages"]).stages) as build:
cache.get(snapshot)
self.assertEqual(build.call_count, 1)
self.assertEqual(json.loads(path.read_text(encoding="utf-8"))["owner"], str(snapshot.raw["master"]["id"]))
path.write_text("[]", encoding="utf-8")
self.assertTrue(StageCache(catalog, path).get(snapshot))
class MapCacheGuiTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.app = W.QApplication.instance() or W.QApplication([])
def wait(self, predicate):
for _ in range(700):
self.app.processEvents()
QTest.qWait(2)
if predicate():
return
self.fail("Qt worker did not finish")
def test_collapsed_maps_remain_cached_on_page_switch_and_poll_manual_refresh_updates(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)
catalog, snapshot = scenario()
client = FakeClient(snapshot)
client.session = Session("http://127.0.0.1/", "synthetic-test-token")
client.persist_session = lambda: None
client.close = lambda: None
window.catalog = catalog
window.engine = Engine(catalog, client, folder / "purchase.json")
window.engine.snapshot = snapshot
window.tabs.setCurrentWidget(window.map_page)
self.wait(lambda: not window.map_render_timer.running)
self.assertTrue(all(not window.maps_tree.topLevelItem(i).isExpanded() for i in range(window.maps_tree.topLevelItemCount())))
original = window.engine.stage_cache.rows
client.value["history"]["unlockStage"]["0102"] = ["1", "2", "3"]
window.tabs.setCurrentWidget(window.slot_page)
with patch("ranch_assistant.stage_cache.stages", side_effect=AssertionError("Page/poll refreshed cached maps")):
window.refresh()
self.wait(lambda: not window.busy)
window.tabs.setCurrentWidget(window.map_page)
self.wait(lambda: not window.map_render_timer.running)
self.assertIs(window.engine.stage_cache.rows, original)
self.assertTrue(window.engine.heartbeat_enabled)
refresh = next(b for b in window.map_page.findChildren(W.QPushButton) if b.text() == "刷新关卡")
refresh.click()
self.wait(lambda: not window.busy and not window.map_render_timer.running)
changed = next(row for row in window.engine.stage_cache.rows if row.stage_id == "0102" and row.level == "2")
self.assertTrue(changed.unlocked)
self.assertTrue((folder / "maps.json").exists())
finally:
window.close()
+165
View File
@@ -0,0 +1,165 @@
import copy
import os
import time
import unittest
from unittest.mock import patch
from ranch_assistant.engine import Engine, demo_snapshot
from ranch_assistant.model import Catalog, Snapshot
NOW = 1800000000
LEVEL = "masterService/masterLevelUpdate"
STAMINA = "masterService/masterCheckTiAdd"
class MasterClient:
def __init__(self, catalog):
self.raw = copy.deepcopy(demo_snapshot(catalog).raw)
self.raw.update(monsters=[], items=[], stacks=[])
self.raw["master"].update(level=1, exp=0, ti=5, timeTi=(NOW - 360) * 1000)
self.calls = []
self.responses = {LEVEL: {"level": 3}, STAMINA: {"ti": 6, "timeTi": NOW * 1000}}
def snapshot(self):
return Snapshot(copy.deepcopy(self.raw))
def call(self, path, payload=None):
self.calls.append((path, payload))
return self.responses[path]
def persist_session(self):
pass
def close(self):
pass
class MasterSyncTests(unittest.TestCase):
def setUp(self):
self.clock = patch("ranch_assistant.model.time.time", return_value=NOW)
self.now = self.clock.start()
self.addCleanup(self.clock.stop)
self.catalog = Catalog()
self.catalog.data = self.catalog.data | {"game_setting": self.catalog.data["game_setting"] | {"tiCD": 360}}
self.client = MasterClient(self.catalog)
self.engine = Engine(self.catalog, self.client)
def test_monitor_settles_stamina_and_preserves_server_result_across_stale_read(self):
snapshot, _, _ = self.engine.poll()
self.assertEqual(snapshot.raw["master"]["ti"], 6)
self.assertEqual(self.client.calls, [(STAMINA, {})])
self.engine.poll()
self.assertEqual(self.engine.snapshot.raw["master"]["ti"], 6)
self.assertEqual(len(self.client.calls), 1)
def test_experience_threshold_requests_server_level_without_starting_automation(self):
self.client.raw["master"].update(exp=self.catalog.data["farm_level"]["4"], timeTi=NOW * 1000)
snapshot, _, _ = self.engine.poll()
self.assertEqual(snapshot.raw["master"]["level"], 3)
self.assertEqual(self.client.calls, [(LEVEL, {})])
self.assertFalse(self.engine.auto)
def test_before_recovery_boundary_and_level_threshold_no_request(self):
self.client.raw["master"].update(exp=self.catalog.data["farm_level"]["2"] - 1,
timeTi=(NOW - 359) * 1000)
self.engine.poll()
self.assertEqual(self.client.calls, [])
self.assertFalse(self.engine.master_sync_due())
self.now.return_value = NOW + 1
self.assertTrue(self.engine.master_sync_due())
self.engine.sync_master()
self.assertEqual(self.engine.snapshot.raw["master"]["ti"], 6)
def test_fresh_consumption_overrides_cached_stamina_and_levels_never_regress(self):
self.client.raw["master"]["exp"] = self.catalog.data["farm_level"]["3"]
self.engine.poll()
self.client.raw["master"].update(ti=2, timeTi=NOW * 1000)
self.engine.read_snapshot()
self.assertEqual(self.engine.snapshot.raw["master"]["ti"], 2)
self.assertEqual(self.engine.snapshot.raw["master"]["level"], 3)
self.assertIsNone(self.engine.master_sync.stamina)
def test_no_progress_and_failures_are_throttled_per_account(self):
self.client.responses[STAMINA] = {"ti": 5, "timeTi": (NOW - 360) * 1000}
with patch("ranch_assistant.master_sync.time.monotonic", return_value=100) as monotonic:
self.engine.poll()
self.engine.poll()
self.assertEqual(len(self.client.calls), 1)
other = Engine(self.catalog, MasterClient(self.catalog))
other.poll()
self.assertEqual(len(other.client.calls), 1)
monotonic.return_value = 130
self.assertTrue(self.engine.master_sync_due())
self.client.call = unittest.mock.Mock(side_effect=RuntimeError("test failure"))
with self.assertRaises(RuntimeError):
self.engine.sync_master()
self.assertFalse(self.engine.master_sync_due())
def test_fast_hatching_never_settles_player_state(self):
self.client.raw["master"]["exp"] = self.catalog.data["farm_level"]["3"]
self.engine.poll(hatch_only=True)
self.assertEqual(self.client.calls, [])
def test_full_stamina_uses_server_timestamp_without_repeated_requests(self):
self.client.raw["master"]["ti"] = 600
self.client.responses[STAMINA] = {"ti": 600, "timeTi": NOW * 1000}
self.engine.poll()
self.engine.poll()
self.assertEqual(len(self.client.calls), 1)
self.assertFalse(self.engine.master_sync_due())
def test_max_level_and_absent_timestamp_do_not_request(self):
self.client.raw["master"].update(level=70, exp=10**9, timeTi=None)
self.engine.poll()
self.assertEqual(self.client.calls, [])
def test_incomplete_stamina_reply_never_fabricates_new_value(self):
self.client.responses[STAMINA] = {"ti": 600}
with self.assertRaisesRegex(ValueError, "ti / timeTi"):
self.engine.poll()
self.assertEqual(self.engine.snapshot.raw["master"]["ti"], 5)
self.assertFalse(self.engine.master_sync_due())
class MasterSyncGuiTests(unittest.TestCase):
def test_recovery_deadline_uses_background_job_without_changing_poll_deadline(self):
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6 import QtWidgets as W
from PySide6.QtTest import QTest
from ranch_assistant.gui import Window
from ranch_assistant.api import Session
from ranch_assistant.tests.test_core import workspace_temp
app = W.QApplication.instance() or W.QApplication([])
with workspace_temp() as folder, patch("ranch_assistant.model.time.time", return_value=NOW):
window = Window(folder)
window.timer.stop()
def wait():
for _ in range(500):
app.processEvents()
QTest.qWait(2)
if not window.busy:
return
self.fail("Master sync worker did not finish")
try:
wait()
client = MasterClient(window.catalog)
client.session = Session("http://127.0.0.1/", "synthetic-test-token")
window.engine = Engine(window.catalog, client)
window.engine.last_heartbeat = time.monotonic()
window.engine.snapshot = client.snapshot()
window.next_poll = float("inf")
window.schedule()
self.assertTrue(window.busy)
wait()
self.assertEqual(window.engine.snapshot.raw["master"]["ti"], 6)
self.assertEqual(client.calls, [(STAMINA, {})])
self.assertEqual(window.next_poll, float("inf"))
self.assertFalse(window.strategy_toggle.isChecked())
self.assertTrue(window.monitoring)
finally:
window.close()
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,136 @@
import os
import time
import unittest
from unittest.mock import patch
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6 import QtWidgets as W
from PySide6.QtTest import QTest
from ranch_assistant.api import Session
from ranch_assistant.engine import Engine, demo_snapshot
from ranch_assistant.gui import Window
from ranch_assistant.model import Catalog, Planner, Policy
from ranch_assistant.policy_io import import_policy, portable_policy
from ranch_assistant.tests.test_core import workspace_temp
from ranch_assistant.tests.test_growth import GrowthClient, NOW
class FourSProtectionTests(unittest.TestCase):
def test_four_s_requires_every_stat_instead_of_average_grade(self):
catalog = Catalog()
snapshot = demo_snapshot(catalog)
mon = snapshot.monsters[101]
mon.update(mode=2, lock=0)
info = catalog.monster(mon["typeId"])
for stat in ("atk", "def", "hp", "dex"):
mon["g" + stat.capitalize()] = info[stat + "_grow_max"]
policy = Policy(strategy="gold", protect_star=6, protect_quality=6)
planner = Planner(catalog)
self.assertEqual(catalog.quality(mon), [4, 4, 4, 4])
self.assertIn("4S", planner.protection_reason(mon, snapshot, policy))
self.assertEqual(planner.disposition(mon, snapshot, policy), "keep")
for stat in ("atk", "def", "hp", "dex"):
with self.subTest(stat=stat):
mon["g" + stat.capitalize()] = info[stat + "_grow_min"]
self.assertEqual(planner.disposition(mon, snapshot, policy), "sell")
self.assertTrue(planner.protected(mon, snapshot, Policy(protect_star=6, protect_quality=4)))
mon["g" + stat.capitalize()] = info[stat + "_grow_max"]
def test_four_s_keeps_locks_unknown_grades_star_guards_and_round_trips(self):
catalog = Catalog()
snapshot = demo_snapshot(catalog)
mon = snapshot.monsters[101]
policy = Policy(protect_star=6, protect_quality=6)
planner = Planner(catalog)
mon["lock"] = 1
self.assertTrue(planner.protected(mon, snapshot, policy))
mon["lock"] = 0
policy.protect_star = 1
self.assertTrue(planner.protected(mon, snapshot, policy))
policy.protect_star = 6
mon["gAtk"] = None
self.assertTrue(planner.protected(mon, snapshot, policy))
self.assertEqual(import_policy(portable_policy(policy, snapshot), snapshot).protect_quality, 6)
class MonitoringGuiTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.app = W.QApplication.instance() or W.QApplication([])
def wait(self, window):
for _ in range(500):
self.app.processEvents()
QTest.qWait(2)
if not window.busy:
return
self.fail("Background job did not finish")
def test_random_intervals_are_redrawn_and_saved_and_old_settings_migrate(self):
with workspace_temp() as folder:
window = Window(folder)
window.timer.stop()
try:
self.wait(window)
self.assertEqual([window.interval.itemData(i) for i in range(window.interval.count())], [30, 60, 120, 300])
with patch("ranch_assistant.gui.random.uniform", side_effect=[0, 29.9]) as draw:
self.assertEqual(window.poll_delay(), 0)
self.assertEqual(window.poll_delay(), 29.9)
self.assertEqual(draw.call_args_list[0].args, (0, 30))
self.assertEqual(draw.call_count, 2)
window.interval.setCurrentIndex(3)
window.save_config(quiet=True)
window.load_config({"interval": 5, "farm": {"stage_id": "bd00"}, "capture_profile": "old.json"})
self.assertEqual(window.interval.currentData(), 30)
self.assertFalse(hasattr(window, "farm"))
self.assertFalse(hasattr(window, "capture_scroll"))
window.load_config()
self.assertEqual(window.interval.currentData(), 300)
window.protect_quality.setCurrentIndex(window.protect_quality.findData(6))
window.save_config(quiet=True)
finally:
window.close()
restored = Window(folder)
restored.timer.stop()
try:
self.wait(restored)
self.assertEqual(restored.interval.currentData(), 300)
self.assertEqual(restored.read_policy().protect_quality, 6)
self.assertFalse(restored.strategy_toggle.isChecked())
finally:
restored.close()
def test_growth_deadline_sync_runs_without_waiting_for_monitor_poll(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)
client = GrowthClient(window.catalog, age=599, grade="S")
client.raw["monsters"][0]["mode"] = 1
client.session = Session("http://127.0.0.1/", "synthetic-test-token")
window.engine = Engine(window.catalog, client)
window.engine.last_heartbeat = time.monotonic()
window.engine.snapshot = client.snapshot()
self.assertFalse(window.engine.growth_sync_due())
window.engine.snapshot.server_offset = 2
client.raw["monsters"][0]["timeStart"] -= 2000
client.stage = 2
window.next_poll = float("inf")
self.assertFalse(window.monitoring)
window.schedule()
self.wait(window)
self.assertTrue(window.monitoring)
self.assertEqual(sum(name == "growth" for name, _ in client.calls), 1)
self.assertEqual(window.engine.snapshot.monsters[501]["mode"], 2)
self.assertEqual(window.catalog.quality_text(window.engine.snapshot.monsters[501]), "S/S/S/S")
self.assertFalse(any(name == "monsterService/monsterSell" for name, _ in client.calls))
self.assertFalse(window.strategy_toggle.isChecked())
self.assertFalse(any("同步孵化" in button.text() for button in window.slot_page.findChildren(W.QPushButton)))
finally:
window.close()
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,77 @@
import os
import unittest
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6 import QtCore as C, QtGui as G, QtWidgets as W
from PySide6.QtTest import QTest
from ranch_assistant.gui import spin
from ranch_assistant.native_widgets import IntegerInput
class NumericWheelTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.app = W.QApplication.instance() or W.QApplication([])
def wheel(self, widget, delta=120):
point = widget.rect().center()
event = G.QWheelEvent(C.QPointF(point), C.QPointF(widget.mapToGlobal(point)),
C.QPoint(), C.QPoint(0, delta), C.Qt.MouseButton.NoButton,
C.Qt.KeyboardModifier.NoModifier, C.Qt.ScrollPhase.NoScrollPhase, False)
self.app.sendEvent(widget, event)
return event
def test_all_number_controls_require_focus_and_release_wheel_for_page_scrolling(self):
host = W.QWidget()
layout = W.QVBoxLayout(host)
other = W.QLineEdit()
layout.addWidget(other)
widgets = [spin(0, 100, 10), spin(0, 100, 10, True), IntegerInput()]
for widget in widgets:
if isinstance(widget, IntegerInput):
widget.setRange(0, 100)
widget.setValue(10)
layout.addWidget(widget)
host.show()
host.activateWindow()
QTest.qWait(10)
try:
for widget in widgets:
with self.subTest(type=type(widget).__name__):
other.setFocus()
self.app.processEvents()
self.assertFalse(self.wheel(widget).isAccepted())
self.assertEqual(widget.value(), 10)
self.assertFalse(widget.hasFocus())
QTest.mouseClick(widget, C.Qt.MouseButton.LeftButton)
self.app.processEvents()
self.assertTrue(widget.hasFocus())
self.wheel(widget)
self.assertEqual(widget.value(), 11)
self.wheel(widget, -120)
self.assertEqual(widget.value(), 10)
other.setFocus()
self.app.processEvents()
self.wheel(widget)
self.assertEqual(widget.value(), 10)
finally:
host.close()
def test_integer_wheel_clamps_and_accumulates_small_steps(self):
widget = IntegerInput()
widget.setRange(0, 2)
widget.show()
widget.activateWindow()
widget.setFocus()
QTest.qWait(10)
try:
self.wheel(widget, 60)
self.assertEqual(widget.value(), 0)
self.wheel(widget, 60)
self.assertEqual(widget.value(), 1)
self.wheel(widget, 1200)
self.assertEqual(widget.value(), 2)
self.wheel(widget, -1200)
self.assertEqual(widget.value(), 0)
finally:
widget.close()
+124
View File
@@ -0,0 +1,124 @@
from dataclasses import asdict
import json
import os
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.daily import DailyPolicy
from ranch_assistant.engine import demo_snapshot
from ranch_assistant.gui import Window
from ranch_assistant.model import Catalog, Policy
from ranch_assistant.policy_io import portable_config, import_config, portable_policy
from ranch_assistant.quests import QuestPolicy
from ranch_assistant.sweeping import SweepPolicy
from ranch_assistant.tests.test_core import workspace_temp
class UnifiedPolicyTests(unittest.TestCase):
def config(self):
return {"policy": asdict(Policy(buy=True, gift_enabled=True, feed_target=900, room_id=999999,
gift_targets={"900": 2}, gift_items={"30001": {"enabled": True, "reserve": 5}})),
"quest_policy": asdict(QuestPolicy(enabled=True, max_money=100, item_reserves={"30001": 6})),
"daily_policy": asdict(DailyPolicy(enabled=True, selected=["mail"])),
"sweep_policy": asdict(SweepPolicy(enabled=True, rules={"0101": {"enabled": True, "level": 3, "limit": 5}}, keep_stamina=22)),
"interval": 120, "overrides": {"1001010": {"sell_money": 151}}, "yield_stars": [1, 2],
"token": "secret-test-only", "account": "private-test-only", "log_sizes": [600, 200]}
def test_all_strategies_round_trip_and_targets_match_other_account(self):
snapshot = demo_snapshot(Catalog())
exported = portable_config(self.config(), snapshot)
text = json.dumps(exported)
for secret in ("secret-test-only", "private-test-only", "999999", '"900"', "log_sizes"):
self.assertNotIn(secret, text)
snapshot.monsters[900]["id"] = 999
config = import_config(exported, snapshot)
self.assertEqual(config["policy"]["feed_targets"], {"999": 1})
self.assertEqual(config["policy"]["gift_targets"], {"999": 2})
self.assertEqual(config["policy"]["feed_target"], 0)
self.assertEqual(config["policy"]["room_id"], 0)
self.assertTrue(config["policy"]["gift_enabled"])
for key in ("quest_policy", "daily_policy", "sweep_policy", "interval", "overrides", "yield_stars"):
self.assertEqual(config[key], self.config()[key])
def test_old_files_import_without_replacing_other_strategy_sections(self):
config = import_config(portable_policy(Policy(protect_quality=6)))
self.assertEqual(list(config), ["policy"])
self.assertEqual(config["policy"]["protect_quality"], 6)
self.assertFalse(config["policy"]["enabled"])
def test_invalid_bundle_rejected_before_applying(self):
exported = portable_config(self.config())
for value in (exported | {"schema": 100}, exported | {"interval": 0},
exported | {"daily_policy": []}, exported | {"yield_stars": [None]},
exported | {"policy": exported["policy"] | {"target_level": "bad"}},
exported | {"sweep_policy": exported["sweep_policy"] | {"rules": {"0101": None}}}):
with self.assertRaises((ValueError, TypeError)):
import_config(value)
class StrategyGuiTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.app = W.QApplication.instance() or W.QApplication([])
def wait(self, window):
for _ in range(500):
self.app.processEvents()
QTest.qWait(2)
if not window.busy:
return
self.fail("Offline task did not finish")
def test_separate_pages_and_unified_import_apply_without_starting_execution(self):
with workspace_temp() as folder:
window = Window(folder)
window.timer.stop()
try:
self.wait(window)
self.assertEqual([window.automation_tabs.tabText(i) for i in range(3)],
["孵蛋策略", "牧场策略", "喂养策略"])
self.assertEqual(window.tabs.tabText(window.tabs.indexOf(window.gift_page)), "自动赠礼")
self.assertTrue(window.gift_page.isAncestorOf(window.gift_enabled))
self.assertTrue(window.feed_scroll.isAncestorOf(window.feed))
value = portable_config(UnifiedPolicyTests().config(), window.engine.snapshot)
path = folder / "portable.json"
path.write_text(json.dumps(value), encoding="utf-8")
with patch("ranch_assistant.gui.W.QFileDialog.getOpenFileName", return_value=(str(path), "")):
window.import_policies()
self.assertFalse(window.strategy_toggle.isChecked())
self.assertFalse(window.engine.auto)
self.assertTrue(window.engine.policy.gift_enabled)
self.assertEqual(window.engine.quest_policy.max_money, 100)
self.assertEqual(window.engine.sweep_policy.keep_stamina, 22)
self.assertEqual(window.engine.daily_policy.selected, ["mail"])
self.assertEqual(window.interval.currentData(), 120)
window.quest_money.setValue(42)
window.gift_liked_only.setChecked(False)
QTest.qWait(400)
self.assertEqual(window.engine.quest_policy.max_money, 42)
self.assertFalse(window.engine.policy.gift_liked_only)
with patch("ranch_assistant.gui.W.QFileDialog.getSaveFileName", return_value=(str(path), "")):
window.export_policies()
exported = json.loads(path.read_text(encoding="utf-8"))
self.assertEqual(import_config(exported, window.engine.snapshot)["quest_policy"]["max_money"], 42)
self.assertFalse(any("保存规则" in b.text() for b in window.findChildren(W.QPushButton)))
finally:
window.close()
def test_gift_only_workflow_does_not_require_hatch_rules(self):
with workspace_temp() as folder:
window = Window(folder)
window.timer.stop()
try:
self.wait(window)
window.ranch_enabled.setChecked(False)
window.gift_enabled.setChecked(True)
with patch.object(window, "refresh"):
window.start_workflow()
self.assertTrue(window.strategy_toggle.isChecked())
finally:
window.close()
+180
View File
@@ -0,0 +1,180 @@
import copy
import os
import time
import unittest
from unittest.mock import patch
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6 import QtCore as C, QtWidgets as W
from PySide6.QtTest import QTest
from ranch_assistant.engine import demo_snapshot
from ranch_assistant.gui import Window
from ranch_assistant.model import Catalog
from ranch_assistant.presentation import monster_rows
from ranch_assistant.ranch_gui import RanchView
from ranch_assistant.tests.test_core import workspace_temp
class RanchTreeTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.app = W.QApplication.instance() or W.QApplication([])
def drain(self, tree):
for _ in range(500):
self.app.processEvents()
if not tree.row_batch.running:
return
QTest.qWait(2)
self.fail("Ranch rows did not finish")
def scenario(self):
catalog = Catalog()
snapshot = demo_snapshot(catalog)
room = snapshot.raw["rooms"][0]
snapshot.raw["rooms"] += [room | {"id": 2, "name": "第二牧场"}, room | {"id": 3, "name": "空牧场"}]
snapshot.raw["monsters"].append(snapshot.monsters[900] | {"id": 901, "roomId": 2})
return catalog, snapshot
def render(self, tree, snapshot, feeds=None, gifts=None):
tree.set_data(snapshot, monster_rows(tree.catalog, snapshot, set()), feeds or {}, gifts or {})
self.drain(tree)
def test_ranch_headers_children_and_refresh_preserve_controls_and_collapse(self):
catalog, snapshot = self.scenario()
tree = RanchView(catalog)
try:
self.render(tree, snapshot)
self.assertEqual(tree.group_items["room:1"].childCount(), 1)
self.assertEqual(tree.group_items["room:2"].childCount(), 1)
self.assertEqual(tree.group_items["room:3"].childCount(), 0)
self.assertEqual(tree.group_items["incubator"].childCount(), 4)
self.assertIn("魔物 1 /", tree.group_items["room:1"].text(0))
self.assertIn("魔物 0 /", tree.group_items["room:3"].text(0))
item = tree.monster_items[900]
check, priority = tree.itemWidget(item, 8), tree.itemWidget(item, 9)
tree.setCurrentItem(item)
tree.group_items["room:1"].setExpanded(False)
updated = copy.deepcopy(snapshot)
updated.monsters[900]["feel"] = 30
self.render(tree, updated, {"900": 2}, {"900": 3})
self.assertIs(tree.monster_items[900], item)
self.assertIs(tree.itemWidget(item, 8), check)
self.assertIs(tree.itemWidget(item, 9), priority)
self.assertTrue(check.isChecked())
self.assertEqual(priority.value(), 2)
self.assertTrue(tree.itemWidget(item, 17).isChecked())
self.assertEqual(tree.itemWidget(item, 18).value(), 3)
self.assertFalse(tree.group_items["room:1"].isExpanded())
self.assertEqual(tree.selected_monster_ids(), [900])
self.assertTrue(item.text(15).startswith("30 /"))
finally:
tree.row_batch.stop()
tree.close()
def test_flat_toggle_room_transfer_and_removed_monsters_keep_correct_ids(self):
catalog, snapshot = self.scenario()
tree = RanchView(catalog)
messages = []
previous = C.qInstallMessageHandler(lambda kind, context, message: messages.append(message))
try:
self.render(tree, snapshot)
tree.set_view(False)
self.render(tree, snapshot)
self.assertEqual(tree.topLevelItemCount(), 6)
self.assertFalse(tree.rootIsDecorated())
self.assertTrue(all(item.parent() is None for item in tree.monster_items.values()))
tree.set_view(True)
self.render(tree, snapshot)
self.assertIs(tree.monster_items[900].parent(), tree.group_items["room:1"])
updated = copy.deepcopy(snapshot)
updated.monsters[900]["roomId"] = 2
updated.raw["monsters"] = [mon for mon in updated.raw["monsters"] if mon["id"] != 901]
self.render(tree, updated)
self.assertNotIn(901, tree.monster_items)
self.assertEqual(tree.group_items["room:1"].childCount(), 0)
self.assertIs(tree.monster_items[900].parent(), tree.group_items["room:2"])
tree.set_view(True, 2)
self.render(tree, updated)
self.assertEqual(set(tree.monster_items), {900})
tree.set_view(False, 2)
self.render(tree, updated)
self.assertEqual(len(tree.monster_items), 5)
self.assertFalse(any("already owned" in message for message in messages))
finally:
C.qInstallMessageHandler(previous)
tree.row_batch.stop()
tree.close()
def test_tree_rules_context_menu_and_double_click_use_monster_ids(self):
with workspace_temp() as folder:
window = Window(folder)
window.timer.stop()
try:
for _ in range(400):
self.app.processEvents()
QTest.qWait(2)
if not window.busy:
break
window.tabs.setCurrentWidget(window.monster_page)
tree = window.monsters
self.drain(tree)
self.assertEqual(window.monster_view.currentData(), 0)
self.assertFalse(window.monster_room.isEnabled())
self.assertTrue(all(item.parent() is None for item in tree.monster_items.values()))
window.monster_view.setCurrentIndex(window.monster_view.findData(1))
self.drain(tree)
self.assertIs(tree.monster_items[900].parent(), tree.group_items["room:1"])
item = tree.monster_items[900]
tree.itemWidget(item, 8).setChecked(True)
tree.itemWidget(item, 9).setValue(4)
tree.itemWidget(item, 17).setChecked(True)
tree.itemWidget(item, 18).setValue(5)
self.assertEqual(window.read_policy().feed_targets, {"900": 4})
self.assertEqual(window.read_policy().gift_targets, {"900": 5})
tree.setCurrentItem(item)
with patch("PySide6.QtWidgets.QMenu.popup"):
window.page_menu(tree.viewport(), C.QPoint(-1, -1), window.monster_page)
lock = next(action for action in window.refresh_menu.actions() if action.text() == "解锁选中魔物")
self.assertTrue(lock.isEnabled())
lock.trigger()
for _ in range(400):
self.app.processEvents()
QTest.qWait(2)
if not window.busy:
break
self.assertFalse(window.engine.snapshot.monsters[900].get("lock"))
with patch("PySide6.QtWidgets.QMessageBox.information") as detail:
tree.itemDoubleClicked.emit(tree.monster_items[900], 1)
self.assertIn("#900", detail.call_args.args[2])
tree.clearSelection()
with patch("PySide6.QtWidgets.QMenu.popup"):
window.page_menu(tree.viewport(), C.QPoint(-1, -1), window.monster_page)
dispatch = next(action for action in window.refresh_menu.actions() if action.text() == "派遣选中魔物…")
self.assertFalse(dispatch.isEnabled())
finally:
window.close()
def test_large_monster_tree_renders_in_batches(self):
catalog, snapshot = self.scenario()
template = snapshot.monsters[900]
snapshot.raw["monsters"] = [template | {"id": 10000 + index} for index in range(500)]
tree = RanchView(catalog)
timer, beats = C.QTimer(), []
timer.setInterval(5)
timer.timeout.connect(lambda: beats.append(time.perf_counter()))
try:
timer.start()
self.render(tree, snapshot)
self.assertEqual(len(tree.monster_items), 500)
self.assertGreater(len(beats), 2)
self.assertLess(max(b - a for a, b in zip(beats, beats[1:])), .25)
finally:
timer.stop()
tree.row_batch.stop()
tree.close()
if __name__ == "__main__":
unittest.main()
+2 -2
View File
@@ -54,7 +54,7 @@ class ResponsivenessTests(unittest.TestCase):
snapshot = demo_snapshot(window.catalog)
template = snapshot.raw["monsters"][-1]
snapshot.raw["monsters"] = [copy.deepcopy(template) | {"id": 1000 + i} for i in range(500)]
with patch.object(window.monsters, "setCellWidget") as cells:
with patch.object(window.monsters, "setItemWidget") as cells:
window.engine.snapshot = snapshot
window.render(snapshot, [])
self.assertEqual(cells.call_count, 0)
@@ -171,7 +171,7 @@ class ResponsivenessTests(unittest.TestCase):
break
self.assertFalse(any(w.busy for w in windows))
self.assertEqual(windows[0].eggs.rowCount(), 200)
self.assertEqual(windows[1].monsters.rowCount(), 0)
self.assertEqual(len(windows[1].monsters.monster_items), 0)
self.assertGreater(len(beats), 10)
self.assertLess(max(b - a for a, b in zip(beats, beats[1:])), .25)
self.assertTrue(any(e["operation"] == "刷新耗时" for e in windows[0].trace.events))
+185
View File
@@ -0,0 +1,185 @@
from dataclasses import asdict
import json
import os
import unittest
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6 import QtCore as C, QtWidgets as W
from PySide6.QtTest import QTest
from ranch_assistant.egg_rules_gui import EggTable
from ranch_assistant.engine import demo_snapshot
from ranch_assistant.gui import Window
from ranch_assistant.inventory_gui import InventoryTable
from ranch_assistant.model import Catalog, EggRule
from ranch_assistant.presentation import monster_rows
from ranch_assistant.ranch_gui import RanchView
from ranch_assistant.tests.test_activities import scenario
from ranch_assistant.tests.test_core import workspace_temp
class RuleEditingTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.app = W.QApplication.instance() or W.QApplication([])
def wait(self, predicate):
for _ in range(800):
self.app.processEvents()
QTest.qWait(2)
if predicate():
return
self.fail("Qt operation did not finish")
def test_egg_controls_sort_numerically_and_edits_stay_with_their_species(self):
catalog = Catalog()
snapshot = demo_snapshot(catalog)
snapshot.raw["items"] = snapshot.eggs(catalog)[:3]
keys = [str(item["typeId"]) for item in snapshot.raw["items"]]
rules = {key: asdict(EggRule(enabled=index != 0, priority=priority, action=action))
for index, (key, priority, action) in enumerate(zip(keys, (10, 2, 1), ("sell", "keep", "feed")))}
table = EggTable(catalog)
try:
table.set_data(snapshot, rules)
self.wait(lambda: not table.row_batch.running)
table.sortItems(4, C.Qt.SortOrder.AscendingOrder)
self.assertEqual([table.cellWidget(i, 4).value() for i in range(3)], [1, 2, 10])
table.sortItems(5, C.Qt.SortOrder.AscendingOrder)
self.assertEqual([table.cellWidget(i, 5).currentText() for i in range(3)], ["保留", "喂养", "派遣"])
table.sortItems(3, C.Qt.SortOrder.DescendingOrder)
self.assertEqual([table.cellWidget(i, 3).isChecked() for i in range(3)], [True, True, False])
key = table.item(0, 0).data(C.Qt.ItemDataRole.UserRole)
table.cellWidget(0, 3).setChecked(False)
self.assertFalse(table.rules[key]["enabled"])
table.set_data(snapshot, table.rules)
self.wait(lambda: not table.row_batch.running)
for i in range(3):
self.assertEqual(table.cellWidget(i, 3).property("egg_type_id"), table.item(i, 0).data(C.Qt.ItemDataRole.UserRole))
self.assertTrue(table.item(i, 1).textAlignment() & C.Qt.AlignmentFlag.AlignHCenter)
self.assertTrue(table.item(i, 2).textAlignment() & C.Qt.AlignmentFlag.AlignHCenter)
self.assertTrue(table.cellWidget(i, 4).alignment() & C.Qt.AlignmentFlag.AlignHCenter)
finally:
table.row_batch.stop()
table.close()
def test_inventory_checkbox_and_reserve_sort_keep_item_rule_identity(self):
catalog = Catalog()
snapshot = demo_snapshot(catalog)
keys = [key for key, row in catalog.data["item_info"].items() if row.get("sellable") and catalog.item_type(key) != 5][:3]
snapshot.raw["items"] = [{"id": 2000 + i, "typeId": int(key), "num": 20} for i, key in enumerate(keys)]
rules = {key: {"enabled": i != 0, "reserve": reserve} for i, (key, reserve) in enumerate(zip(keys, (10, 2, 1)))}
table = InventoryTable(catalog)
try:
table.set_data(snapshot, rules)
self.wait(lambda: not table.row_batch.running)
table.sortItems(7, C.Qt.SortOrder.AscendingOrder)
self.assertEqual([table.cellWidget(i, 7).value() for i in range(3)], [1, 2, 10])
key = table.item(0, 0).data(C.Qt.ItemDataRole.UserRole)
table.cellWidget(0, 7).setValue(30)
self.assertEqual(table.rules[key]["reserve"], 30)
self.assertEqual([table.cellWidget(i, 7).value() for i in range(3)], [2, 10, 30])
table.sortItems(6, C.Qt.SortOrder.DescendingOrder)
self.assertEqual([table.cellWidget(i, 6).isChecked() for i in range(3)], [True, True, False])
for i in range(3):
self.assertEqual(table.cellWidget(i, 6).property("item_type"), table.item(i, 0).data(C.Qt.ItemDataRole.UserRole))
finally:
table.row_batch.stop()
table.close()
def test_monster_priority_and_checkbox_sort_in_grouped_and_flat_views(self):
catalog = Catalog()
snapshot = demo_snapshot(catalog)
template = snapshot.monsters[900]
snapshot.raw["monsters"] = [template | {"id": mid} for mid in (900, 901, 902)]
tree = RanchView(catalog)
try:
for grouped in (True, False):
tree.set_view(grouped)
tree.set_data(snapshot, monster_rows(catalog, snapshot, set()), {"900": 10, "901": 2, "902": 1}, {"901": 2})
self.wait(lambda: not tree.row_batch.running)
tree.sortByColumn(9, C.Qt.SortOrder.AscendingOrder)
self.app.processEvents()
parent = tree.group_items["room:1"] if grouped else tree.invisibleRootItem()
self.assertEqual([parent.child(i).data(0, C.Qt.ItemDataRole.UserRole) for i in range(3)], [902, 901, 900])
tree.sortByColumn(17, C.Qt.SortOrder.DescendingOrder)
self.app.processEvents()
self.assertEqual(parent.child(0).data(0, C.Qt.ItemDataRole.UserRole), 901)
self.assertTrue(tree.monster_items[901].textAlignment(2) & C.Qt.AlignmentFlag.AlignHCenter)
finally:
tree.row_batch.stop()
tree.close()
def test_sweep_checked_rows_and_limits_sort_without_reset_on_refresh(self):
with workspace_temp() as folder:
window = Window(folder)
window.timer.stop()
try:
self.wait(lambda: not window.busy)
catalog, snapshot = scenario()
window.catalog = catalog
window.engine.catalog = catalog
window.engine.snapshot = snapshot
window.render_maps()
self.wait(lambda: not window.map_render_timer.running)
first, second = window._map_items["0101"], window._map_items["0102"]
first.setCheckState(0, C.Qt.CheckState.Checked)
window.maps_tree.itemWidget(first, 8).setValue(10)
window.maps_tree.itemWidget(second, 8).setValue(2)
window.maps_tree.sortByColumn(8, C.Qt.SortOrder.AscendingOrder)
self.app.processEvents()
self.assertIs(first.parent().child(0), second)
window.maps_tree.sortByColumn(0, C.Qt.SortOrder.DescendingOrder)
window.render_maps()
self.wait(lambda: not window.map_render_timer.running)
self.assertIs(first.parent().child(0), first)
self.assertTrue(window.map_rules["0101"]["enabled"])
self.assertEqual(window.map_rules["0101"]["limit"], 10)
finally:
window.close()
def test_all_form_rules_autosave_and_restore_without_save_buttons_or_starting(self):
with workspace_temp() as folder:
window = Window(folder)
window.timer.stop()
try:
self.wait(lambda: not window.busy)
labels = [button.text() for button in window.findChildren(W.QPushButton)]
self.assertFalse(any(label in labels for label in ("保存规则", "保存设置", "保存当前配置")))
window.keep_money.setValue(4321)
window.protect_quality.setCurrentIndex(window.protect_quality.findData(6))
window.quest_money.setValue(77)
window.map_keep_ti.setValue(23)
window.gift_liked_only.setChecked(False)
self.wait(lambda: not window.auto_save_timer.isActive())
saved = json.loads((folder / "settings.json").read_text(encoding="utf-8"))
self.assertEqual(saved["policy"]["keep_money"], 4321)
self.assertEqual(saved["policy"]["protect_quality"], 6)
self.assertFalse(saved["policy"]["gift_liked_only"])
self.assertEqual(saved["quest_policy"]["max_money"], 77)
self.assertEqual(saved["sweep_policy"]["keep_stamina"], 23)
self.assertEqual(window.engine.policy.keep_money, 4321)
self.assertFalse(window.monitoring)
self.assertFalse(window.strategy_toggle.isChecked())
window.reserve_eggs.setText("1001010:")
self.wait(lambda: not window.auto_save_timer.isActive())
self.assertEqual(json.loads((folder / "settings.json").read_text(encoding="utf-8")), saved)
self.assertTrue(window.engine.heartbeat_enabled)
window.reserve_eggs.setText("1001010:2")
self.wait(lambda: not window.auto_save_timer.isActive())
self.assertEqual(window.engine.policy.reserved_eggs, {"1001010": 2})
finally:
window.close()
restored = Window(folder)
restored.timer.stop()
try:
self.wait(lambda: not restored.busy)
self.assertEqual(restored.read_policy().keep_money, 4321)
self.assertEqual(restored.read_policy().protect_quality, 6)
self.assertEqual(restored.read_policy().reserved_eggs, {"1001010": 2})
self.assertFalse(restored.auto_save_timer.isActive())
finally:
restored.close()
if __name__ == "__main__":
unittest.main()
@@ -194,9 +194,9 @@ class ManualGuiTests(unittest.TestCase):
self.assertEqual(window.eggs.item(row, 2).text(), "0")
self.assertTrue(window.eggs.cellWidget(row, 3).isChecked())
window.tabs.setCurrentWidget(window.monster_page)
row = next(i for i in range(window.monsters.rowCount()) if window.monsters.item(i, 0).text() == "900")
window.monsters.cellWidget(row, 8).setChecked(True)
window.monsters.cellWidget(row, 9).setValue(1)
item = window.monsters.monster_items[900]
window.monsters.itemWidget(item, 8).setChecked(True)
window.monsters.itemWidget(item, 9).setValue(1)
self.assertEqual(window.read_policy().feed_targets, {"900": 1})
self.assertFalse(window.server.isVisible())
window.save_config()
@@ -209,7 +209,7 @@ class ManualGuiTests(unittest.TestCase):
self.assertTrue(restored.egg_rules[key]["enabled"])
self.assertEqual(restored.egg_rules[key]["action"], "feed")
self.assertEqual(restored.feed_targets, {"900": 1})
self.assertFalse(restored.execute.isChecked())
self.assertFalse(restored.strategy_toggle.isChecked())
finally:
restored.close()
@@ -276,8 +276,8 @@ class ManualGuiTests(unittest.TestCase):
self.wait(window)
def select(mid):
window.tabs.setCurrentWidget(window.monster_page)
row = next(i for i in range(window.monsters.rowCount()) if window.monsters.item(i, 0).text() == str(mid))
window.monsters.selectRow(row)
window.monsters.clearSelection()
window.monsters.setCurrentItem(window.monsters.monster_items[mid])
select(101)
with patch.object(gui.W.QMessageBox, "question", return_value=W.QMessageBox.StandardButton.No):
window.request_monster_action("sell")
+34 -17
View File
@@ -122,34 +122,51 @@ class V11GuiTests(unittest.TestCase):
self.assertIn("经验", window.summary.text())
self.assertNotIn("真实", window.data_summary.text())
self.assertIn("退出登录并清除登录记录", window.log.toPlainText() + " ".join(b.text() for b in window.tabs.widget(0).findChildren(W.QPushButton)))
self.assertEqual([window.inventory_tabs.tabText(i) for i in range(window.inventory_tabs.count())],
["魔物蛋", "可使用", "消耗品", "材料", "其他", "装备"])
for category in window.inventory_tables:
key = next(key for key in window.catalog.data["item_info"] if window.catalog.item_type(key) == category)
window.engine.snapshot.raw["items"].append({"id": 4000 + category, "typeId": int(key), "num": 2})
self.assertTrue(all(table.rowCount() == 0 for table in window.inventory_tables.values()))
window.tabs.setCurrentWidget(window.inventory_tabs)
window.inventory_tabs.setCurrentIndex(1)
self.wait(window)
for _ in range(80):
self.app.processEvents()
for index, (category, inventory) in enumerate(window.inventory_tables.items(), 1):
window.inventory_tabs.setCurrentIndex(index)
while inventory.row_batch.running:
QTest.qWait(2)
self.assertGreater(window.inventory.rowCount(), 1)
egg = window.engine.snapshot.eggs(window.catalog)[0]
egg_row = next(i for i in range(window.inventory.rowCount()) if window.inventory.item(i, 0).data(C.Qt.ItemDataRole.UserRole) == str(egg["typeId"]))
self.assertEqual(window.inventory.item(egg_row, 1).text(), window.catalog.monster(egg["typeId"])["name"])
self.assertGreater(inventory.rowCount(), 0)
for row in range(inventory.rowCount()):
key = inventory.item(row, 0).data(C.Qt.ItemDataRole.UserRole)
self.assertEqual(window.catalog.item_type(key), category)
key = str(window.catalog.monster(window.engine.snapshot.monsters[900]["typeId"])["like"].keys().__iter__().__next__())
window.engine.snapshot.raw["items"].append({"id": 3000, "typeId": int(key), "num": 3})
window.inventory.set_data(window.engine.snapshot, {})
for _ in range(100):
self.app.processEvents()
category = window.catalog.item_type(key)
inventory = window.inventory_tables[category]
window.inventory_tabs.setCurrentIndex(list(window.inventory_tables).index(category) + 1)
while inventory.row_batch.running:
QTest.qWait(2)
row = next(i for i in range(window.inventory.rowCount()) if window.inventory.item(i, 0).data(C.Qt.ItemDataRole.UserRole) == key)
window.inventory.cellWidget(row, 6).setChecked(True)
row = next(i for i in range(inventory.rowCount()) if inventory.item(i, 0).data(C.Qt.ItemDataRole.UserRole) == key)
inventory.cellWidget(row, 6).setChecked(True)
self.assertTrue(window.read_policy().gift_items[key]["enabled"])
search = window.inventory_tabs.currentWidget().findChild(W.QLineEdit)
search.setText("no-such-inventory-item")
while inventory.row_batch.running:
QTest.qWait(2)
self.assertEqual(inventory.rowCount(), 0)
search.clear()
while inventory.row_batch.running:
QTest.qWait(2)
row = next(i for i in range(inventory.rowCount()) if inventory.item(i, 0).data(C.Qt.ItemDataRole.UserRole) == key)
self.assertTrue(inventory.cellWidget(row, 6).isChecked())
window.tabs.setCurrentWidget(window.room_page)
for _ in range(100):
self.app.processEvents()
QTest.qWait(2)
target_row = next(i for i in range(window.monsters.rowCount()) if window.monsters.item(i, 0).text() == "900")
window.monsters.cellWidget(target_row, 17).setChecked(True)
target_item = window.monsters.monster_items[900]
window.monsters.itemWidget(target_item, 17).setChecked(True)
self.assertIn("900", window.read_policy().gift_targets)
window.monster_view.setCurrentIndex(1)
self.assertTrue(window.rooms_table.isHidden())
self.assertFalse(window.monsters.rootIsDecorated())
self.assertTrue(all(item.parent() is None for item in window.monsters.monster_items.values()))
finally:
window.close()
@@ -189,7 +206,7 @@ class V11GuiTests(unittest.TestCase):
path.write_text(json.dumps(portable_policy(policy, window.engine.snapshot)), encoding="utf-8")
with patch("ranch_assistant.gui.W.QFileDialog.getOpenFileName", return_value=(str(path), "")):
window.import_policies()
self.assertFalse(window.execute.isChecked())
self.assertFalse(window.strategy_toggle.isChecked())
self.assertFalse(window.read_policy().gift_enabled)
finally:
window.close()
+1 -1
View File
@@ -61,7 +61,7 @@ tables["activity_info"] = {k: v for k, v in tables["activity_info"].items() if k
# 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", "monGiftTime", "monGiftMax", "masterMaxLevel") or k.startswith("loopTask") or k.endswith("_xyz")}
tables["game_setting"] = {k: v for k, v in tables["game_setting"].items() if k in ("monExpScale", "xyz", "xyz1", "cityInfo", "upStarAdd", "maxLike", "vipReward", "monGiftTime", "monGiftMax", "masterMaxLevel", "tiCD", "tiFirst", "tiLevelAdd", "tiTotalMax") or k.startswith("loopTask") or k.endswith("_xyz")}
task_fields = {"type", "typeId", "name", "des", "city", "closed", "condition", "startStep", "reward"}
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} |