fix: keep automatic cultivation on one stable primary per species

This commit is contained in:
AttilaNet
2026-11-13 08:51:03 +08:00
parent 01ad2e3ab9
commit 4fbe895999
35 changed files with 2069 additions and 322 deletions
+6
View File
@@ -58,6 +58,12 @@ jobs:
PY
- name: Install Web dependencies only
run: python -m pip install -r ranch_web/requirements.txt
- name: Offline primary cultivation and resource admission regression
run: |
python -B -m unittest \
ranch_assistant.tests.test_species_retention_limits \
ranch_assistant.tests.test_primary_cultivation \
ranch_assistant.tests.test_primary_resource_admission -v
- name: Offline updater and task log regression
run: python -B -m unittest ranch_web.tests.test_updates ranch_web.tests.test_web_updater ranch_web.tests.test_private_updates ranch_web.tests.test_web_updater_package ranch_web.tests.test_activity ranch_web.tests.test_task_logs -v
- name: Offline account recovery regression
+1 -1
View File
@@ -1,6 +1,6 @@
FROM python:3.12-slim-bookworm
ARG WEB_VERSION=2.0.6
ARG WEB_VERSION=2.0.7
ARG VCS_REF=unknown
LABEL org.opencontainers.image.source="https://github.com/attilanet/myrzx_bot" \
org.opencontainers.image.title="myrzx_bot Web" \
+9 -9
View File
@@ -1,11 +1,11 @@
# 牧羊人之心Bot
本轮 Web 发布目标 **2.0.6**,源码入口为 `main`;原生 PySide6 桌面正式版本保留 **1.2.0**(`v1.2.0`)。两者的适配资料基线均为《牧羊人之心》Android **1.9.68**。
本轮 Web 发布目标 **2.0.7**,源码入口为 `main`;原生 PySide6 桌面正式版本保留 **1.2.0**(`v1.2.0`)。两者的适配资料基线均为《牧羊人之心》Android **1.9.68**。
支持多账号独立运行、牧场培养、每日事务、主线与委托推进、近似战斗模拟、探险、扫荡及本地掉落分析,能力与验证限制见下文。
## 运行指引
### Web 2.0.6(main)
### Web 2.0.7(main)
Windows 使用 Python 3.12+,在项目根目录执行:
@@ -19,7 +19,7 @@ py -3 -m venv .venv-web
Web 无需 Node/npm 或 PySide6,数据独立保存在 `local_state/ranch_web`。Linux Python 启动、离线演示与环境配置见 [Web 运行说明](ranch_web/README.md);单服务 Docker、`/data` 持久化、子路径反代与宿主机受控更新见 [Web 部署说明](deploy/web/README.md)。
**2.0.6** 调整所有策略表单的标签与控件布局:勾选框位于文字左侧,普通字段标签放在输入框上方,每日领取项目独立分组,宽屏和窄屏均保持紧凑。通过“帮助 → 检查版本更新…”安装,详见 [发布说明](analysis/RELEASE_2_0_6.md)。
**2.0.7** 修复同种重复魔物被继续喂养的问题:主培养固定为已养成的高等级魔物,更优资质只作备用;自动喂养、赠礼、潜能突破仅作用于主培养。已启用孵蛋规则按主培养1只、严格更优备用最多1只整理。通过“帮助 → 检查版本更新…”安装,详见 [发布说明](analysis/RELEASE_2_0_7.md)。
### 桌面 1.2.0
@@ -36,7 +36,7 @@ Web 无需 Node/npm 或 PySide6,数据独立保存在 `local_state/ranch_web`
| 组件与版本 | 《牧羊人之心》Android 基线 | 入口与状态 |
| --- | --- | --- |
| Web 2.0.6 | 1.9.68 | 本轮发布目标;源码入口 `main`,`Start_Ranch_Web.cmd` / `sh start-web.sh` |
| Web 2.0.7 | 1.9.68 | 本轮发布目标;源码入口 `main`,`Start_Ranch_Web.cmd` / `sh start-web.sh` |
| 桌面 1.2.0(`v1.2.0`) | 1.9.68 | 当前桌面版本;`Start_Ranch_Helper.cmd` / `python -m ranch_assistant` |
| 桌面 1.1.1(`v1.1.1`) | 1.9.68 | 历史正式版本,1.1 系列修复与界面更新 |
| 桌面 1.1.0(`v1.1.0`) | 1.9.68 | 历史已发布版本 |
@@ -44,9 +44,9 @@ Web 无需 Node/npm 或 PySide6,数据独立保存在 `local_state/ranch_web`
本表记录适配资料基线,不代表其他客户端版本兼容或全部功能已完成实机验收。Docker 镜像以标签流水线成功结果为准,在线更新依赖对应 GitHub Release 条目;详见 [部署说明](deploy/web/README.md)。
## Web 2.0.6 主要功能与分类日志
## Web 2.0.7 主要功能与分类日志
2.0.6 将 2.0.2 的日志界面改为所有功能页共用原有底部日志区,切换页签只显示当前账号、当前功能的日志;取消总日志/全部模式及页内日志框。操作说明见 [2.0.6 发布说明](analysis/RELEASE_2_0_6.md)。其余功能沿用现有实现。
2.0.7 保留自 2.0.3 起的单一底部日志区,切换页签只显示当前账号、当前功能的日志,不提供总日志或页内日志框。本版重点修复同种重复培养,详见 [2.0.7 发布说明](analysis/RELEASE_2_0_7.md)。
- **原布局与15页**:沿用桌面页面顺序、账号页签、顶部玩家数值与统一启停、可调整日志区。
- **多账号与独立后台**:各账号隔离并行、同账号请求串行;关闭网页或退出管理登录后,服务端继续监控及已开启的策略。
@@ -60,7 +60,7 @@ Web 无需 Node/npm 或 PySide6,数据独立保存在 `local_state/ranch_web`
连接状态区分在线、临时故障重试、游戏会话失效与未连接,显示最后成功通信及下次重试时间,旧快照标注为缓存。临时故障先停止策略,再退避执行只读探测;会话失效时停止游戏轮询,按自动重登设置等待,或手动恢复、重新登录。手动选服、恢复会话及自动重登成功后,均自动执行已勾选功能,可在顶部停止。获取区服候选或登录失败不视为成功;未确认的写操作不自动重发,页面轮询不会清除游戏连接错误。
战斗模拟仍为近似模型,特殊关卡并非全部支持。本版验证结果统一见 [发布说明](analysis/RELEASE_2_0_6.md#验证),历史记录见 [Web 验证说明](ranch_web/README.md#离线验证);离线验证不代表真实游戏 API 或生产升级/回滚验收。
战斗模拟仍为近似模型,特殊关卡并非全部支持。本版验证结果统一见 [发布说明](analysis/RELEASE_2_0_7.md#验证),历史记录见 [Web 验证说明](ranch_web/README.md#离线验证);离线验证不代表真实游戏 API 或生产升级/回滚验收。
## 桌面 1.2.0 功能基线
@@ -73,9 +73,9 @@ Web 无需 Node/npm 或 PySide6,数据独立保存在 `local_state/ranch_web`
| 分类背包 | 魔物蛋、可使用物品、消耗品、材料、其他、装备分别展示;支持搜索和排序。每种蛋可配置孵化开关、优先级、孵出后去向、补货下限/目标及市场;物品可配置赠礼开关和保留数量。 |
| 牧场与魔物管理 | 默认平铺全部魔物,可切换为按牧场折叠分组;显示容量、空位、普通等级上限、同种突破、突破经验、潜能阶段、资质、参考属性、好感上限及喜欢的物品。支持详情查看、多选锁定/解锁、派遣、指定喂养,以及确认费用后新建牧场。 |
| 自动孵蛋与补货 | 按手动规则完成金币市场买蛋/抽蛋、孵化、成长同步、成熟收取、派遣或喂养;默认只十连,可单独开启“允许单抽”,遵守金币保留和每日购蛋额度。空坑按优先级独立随机1~2秒装填,不受整体刷新间隔影响。 |
| 资质保留与经验喂养 | “背包 → 魔物蛋”的“牧场保留”默认1,是最低保留数量,0表示关闭数量保护;同种数量跨牧场及孵化批次统一保底。锁定、星级/资质保护仍可让实际保留数超过该值;资质提升依次按S项数、A项数、B项数、四项成长各自归一化后的平均值,与牧场已保留的同种最高资质比较,严格更高才额外保留,同分不额外保留,不自动解锁或强删旧魔物。经验喂养遵守普通等级上限;同种突破最高4级,每只同种素材增加1点突破经验,与潜能阶段分开计算。 |
| 资质保留与经验喂养 | 已启用种类固定保留主培养1只与严格更优资质备用最多1只;备用只保留,不自动培养。新备用更优时先派遣旧备用,同分或更差不继续收取为备用。自动经验及同种突破只喂主培养,主培养到当前上限不会转喂同种其他魔物。锁定、在队、装备及委托保留等硬保护仍有效,受保护的多余魔物显示阻塞原因,不自动解锁。 |
| 自动突破与探险 | 牧场的“潜能突破设置”可定位目标及优先级列;勾选后先补满四项潜能、再提升潜能阶段,消耗对应元素材料并遵守物品/委托保留量,不购买材料、不消耗金币或氪金。顶部策略开启后自动领取已完成的探险奖励;再次出发默认关闭,按队配置地区、保留体力和队员。不花钱开队或召回;未知请求持久化,新快照确认前不重发,停止策略后继续只读刷新。 |
| 自动赠礼与好感培养 | 在背包选择物品、牧场选择目标后自动赠礼;跳过冷却目标,连续处理其他可送目标,在本地倒计时并到期核对状态。支持喜欢物品筛选、库存保留及当前好感上限。可在本地自动为每种魔物选择唯一培养代表,依次按等级、好感、成长资质比较,完全相同时随机选定并记住。 |
| 自动赠礼与好感培养 | 自动与手动目标模式都只向同种主培养赠礼;手动模式要求主培养本身已勾选,不用备用选择代替授权。冷却、满好感或忙碌时不转送同种备用;其他种类符合条件的主培养仍可处理。主培养选择按等级、好感、资质,建立后不因同等级新魔物资质更高而换人。 |
| 每日事务 | 查看并领取每日签到礼包、七日签到、累计奖励、已有VIP日奖和邮件附件;支持手动领取及按勾选项目自动领取。 |
| 自动主线 | 默认显示当前进行中、待接取及待领奖的主线任务,可按类别、状态和关键词组合筛选,另行查看未解锁或已完成任务;展示位置、NPC、需求、对话和阻塞原因。推进已支持的接取、线性对话、交付、领奖与任务补链。材料、蛋或击杀不足时,按已知来源规划普通地图收集;开图受前置、资源和战斗能力限制。 |
| 自动委托 | 根据每日剩余次数、城市与库存接取委托,推进已支持的步骤并领奖;显示金币和氪金奖励,金币、道具及魔物提交可分别限制。实战委托已接入任务战斗调度,须开启对应选项并通过所选模式的能力检查;设置仍在“自动委托”。 |
+26
View File
@@ -0,0 +1,26 @@
# Web 2.0.7 发布说明
Web **2.0.7** 修复自动培养在主培养达到上限后继续喂养同种重复魔物的问题,并区分主培养与资质备用。游戏资料基线 **1.9.68**,桌面版仍为 **1.2.0**。
## 资源目标修复
- 主培养优先选择牧场已养成的高等级魔物。建立后,同等级新魔物不会仅因资质更好而抢占培养身份;只有更高等级的已有魔物或主培养确实消失,才重新确认培养身份。
- 自动经验喂养、同种突破喂养、赠礼、潜能材料及自动突破都只面向主培养。满级、当前上限、冷却、满好感或忙碌不会导致资源转向同种备用。
- 手动目标模式仍要求主培养本身被勾选;历史配置中勾选了备用,不会据此自动给未勾选主培养赠礼。
- 每个已启用孵蛋规则的种类固定保留主培养1只和严格更优的资质备用最多1只。备用只保留,不自动培养。更好的新备用替换旧备用;同分保留已有备用,新孵出的同分副本派遣。
- 资质比较先看 S 项数,再比较四项各自归一化后的等权成长,避免生命数值量级压过其他属性。
- 旧配置不需重新勾选新开关才能获得修复。旧保留数量和更优资质开关不再使已启用种类保留无限副本。
- 整理涵盖已启用种类的现有可处理重复魔物,替换备用时先派遣旧备用,再收取新备用。锁定、在队、装备、探索与委托等硬保护仍保留;受保护副本显示原因,不自动解锁或强行派遣。
## 升级
正式版本 `v2.0.7`,镜像 `ghcr.io/attilanet/myrzx_bot-web:v2.0.7`。通过“帮助 → 检查版本更新…”安装,完成后刷新浏览器。新版本继续保留原底部分类日志、居中加载反馈及紧凑表单。
## 验证
- 相关核心回归 210 条通过,包含 87 条新增主培养选择、限额保留和资源提交检查。覆盖主培养满级/冷却/探险、旧勾选与旧数量配置、首次收取、备用替换、重复副本清理和请求待核对恢复。
- Web 后端 19 个模块共 338 条:335 条通过,3 条因 Windows 的 POSIX 权限或符号链接条件跳过,无失败或错误。
- 全量 Edge 浏览器回归 73 条通过;最后的探险占用修复后,另复跑 2 条受影响检查通过,不重复计入 73 条。
- 新增的 87 条回归纳入正式镜像流水线;独立更新器资产的 3 份源码与暂存 Git 内容逐字节一致。
本次使用合成快照和离线客户端验证,不向真实游戏提交派遣、喂养、赠礼或突破请求,也不手动部署 X99。
+2 -2
View File
@@ -1,11 +1,11 @@
name: ranch-web
services:
web:
image: ${RANCH_WEB_IMAGE:-ghcr.io/attilanet/myrzx_bot-web:v2.0.6}
image: ${RANCH_WEB_IMAGE:-ghcr.io/attilanet/myrzx_bot-web:v2.0.7}
build:
context: .
args:
WEB_VERSION: ${RANCH_WEB_BUILD_VERSION:-2.0.6}
WEB_VERSION: ${RANCH_WEB_BUILD_VERSION:-2.0.7}
user: "10001:10001"
init: true
restart: unless-stopped
+10 -10
View File
@@ -1,8 +1,8 @@
# Web 2 Linux Docker 部署与更新
当前更新示例以 `v2.0.6` 为目标;下文 2.0.1 首次初始化步骤保留历史版本。游戏资料基线为 `1.9.68`,桌面版保留 `1.2.0`。镜像流水线成功、Git tag 与 GitHub Release 是不同的发布步骤:在线更新必须等对应镜像及非草稿、非预发布的 Release 均发布后才能使用。私有仓库未获授权返回 404 属于访问失败,不代表没有版本;只有成功读取列表且没有稳定 2.x 时才显示“暂无正式版”。
当前更新示例以 `v2.0.7` 为目标;下文 2.0.1 首次初始化步骤保留历史版本。游戏资料基线为 `1.9.68`,桌面版保留 `1.2.0`。镜像流水线成功、Git tag 与 GitHub Release 是不同的发布步骤:在线更新必须等对应镜像及非草稿、非预发布的 Release 均发布后才能使用。私有仓库未获授权返回 404 属于访问失败,不代表没有版本;只有成功读取列表且没有稳定 2.x 时才显示“暂无正式版”。
已在 2.0.1 完成私有仓库和 GHCR 认证的部署,可在 2.0.6 稳定 Release 与正式镜像就绪后直接通过“帮助 → 检查版本更新…”升级,无需先安装 2.0.2、重复初始化或替换宿主机更新器。尚未接入私有在线更新的宿主机才需参考下文“已有宿主机首次初始化”。
已在 2.0.1 完成私有仓库和 GHCR 认证的部署,可在 2.0.7 稳定 Release 与正式镜像就绪后直接通过“帮助 → 检查版本更新…”升级,无需先安装 2.0.2、重复初始化或替换宿主机更新器。尚未接入私有在线更新的宿主机才需参考下文“已有宿主机首次初始化”。
## 容器与持久化
@@ -19,7 +19,7 @@ sudo install -m 0600 -o root -g root deploy/web/image.env.example .image.env
sudoedit .env .image.env
```
在 `.env` 填入独立的 `RANCH_WEB_PASSWORD`,这是 Web 管理密码,不是游戏密码;`.image.env` 选择 `RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.6`,需确认对应镜像已发布后再 pull。Compose 默认只发布到宿主机 `127.0.0.1:8765`,容器内监听 `0.0.0.0:8765` 并强制管理密码。使用域名反代时,同时配置 `RANCH_WEB_ALLOWED_HOSTS` 与 `RANCH_WEB_ALLOWED_ORIGINS`;TLS 入口设置 `RANCH_WEB_SECURE_COOKIE=true`。代理保留正确的 Host,写请求依赖来源校验。
在 `.env` 填入独立的 `RANCH_WEB_PASSWORD`,这是 Web 管理密码,不是游戏密码;`.image.env` 选择 `RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.7`,需确认对应镜像已发布后再 pull。Compose 默认只发布到宿主机 `127.0.0.1:8765`,容器内监听 `0.0.0.0:8765` 并强制管理密码。使用域名反代时,同时配置 `RANCH_WEB_ALLOWED_HOSTS` 与 `RANCH_WEB_ALLOWED_ORIGINS`;TLS 入口设置 `RANCH_WEB_SECURE_COOKIE=true`。代理保留正确的 Host,写请求依赖来源校验。
`/opt/ranch-web/data` 挂到容器 `/data`,包括账号、加密会话与密钥、配置、SQLite 统计和更新请求;独立于桌面数据。心跳控制目录独立只读挂到 `/run/ranch-updater`。使用 bind mount 的目录必须预先创建,Compose 不会悄悄创建 root 所有、容器无法写入的目录。默认容器用户 `10001:10001`,根文件系统只读,临时文件写到 `/tmp`。不要对现有账号目录重新初始化密钥。
@@ -51,7 +51,7 @@ Web 只读检查官方 GitHub Releases;默认只接受 `v2.MINOR.PATCH`,跳
### 已完成 2.0.1 初始化的宿主机
`v2.0.6` 稳定 Release 与正式镜像发布后,用户打开“帮助 → 检查版本更新…”,检查到 2.0.6 后手动提交更新请求,可从 2.0.1 直接安装。现有私有仓库认证、GHCR 登录与宿主机更新器继续使用;Web 按钮仍要求有效心跳及 `accept_web_requests=true`。请求显示 `pending` 只表示已提交,宿主机完成备份、安装及健康检查后才确认成功;升级完成后刷新网页以加载新版界面,底部日志默认收起。Windows 或未启用执行器时仍仅可检查版本。自动安装默认关闭。
`v2.0.7` 稳定 Release 与正式镜像发布后,用户打开“帮助 → 检查版本更新…”,检查到 2.0.7 后手动提交更新请求,可从 2.0.1 直接安装。现有私有仓库认证、GHCR 登录与宿主机更新器继续使用;Web 按钮仍要求有效心跳及 `accept_web_requests=true`。请求显示 `pending` 只表示已提交,宿主机完成备份、安装及健康检查后才确认成功;升级完成后刷新网页以加载新版界面,底部日志默认收起。Windows 或未启用执行器时仍仅可检查版本。自动安装默认关闭。
### 全新宿主机准备
@@ -68,20 +68,20 @@ python3 -B /opt/ranch-web/updater.pyz --version
### 已有宿主机首次初始化(用户自行执行)
以下保留 2.0.1 引入私有在线更新时的初始化步骤与 Release 链接,仅供尚未初始化的宿主机参考;已完成私有仓库和 GHCR 认证的部署无需重做。步骤中的 `v2.0.1` 是首次初始化的历史目标,当前应用更新目标为 `v2.0.6`。
以下保留 2.0.1 引入私有在线更新时的初始化步骤与 Release 链接,仅供尚未初始化的宿主机参考;已完成私有仓库和 GHCR 认证的部署无需重做。步骤中的 `v2.0.1` 是首次初始化的历史目标,当前应用更新目标为 `v2.0.7`。
前提是原有 `/opt/ranch-web` Compose 部署、数据目录及 `/etc/ranch-web-updater.toml` 均已存在,配置仍由 root 持有。保留原有数据和配置,不重新初始化密钥;数据目录由 `10001:10001` 持有。以下仅初始化在线更新器,不需要复制项目源码或 Compose。
1. 用户登录有私有仓库读取权限的 GitHub 账号,从 [当前正式 Release](https://github.com/attilanet/myrzx_bot/releases/tag/v2.0.6) 下载 `updater.pyz` 和 `SHA256SUMS`,放到宿主机临时目录。确认 Release 已发布且镜像可读取,在下载目录执行 `sha256sum -c SHA256SUMS` 后安装:
1. 用户登录有私有仓库读取权限的 GitHub 账号,从 [当前正式 Release](https://github.com/attilanet/myrzx_bot/releases/tag/v2.0.7) 下载 `updater.pyz` 和 `SHA256SUMS`,放到宿主机临时目录。确认 Release 已发布且镜像可读取,在下载目录执行 `sha256sum -c SHA256SUMS` 后安装:
```sh
sudo install -m 0644 -o root -g root updater.pyz /opt/ranch-web/updater.pyz
python3 -B /opt/ranch-web/updater.pyz --help
python3 -B /opt/ranch-web/updater.pyz --version
python3 -B /opt/ranch-web/updater.pyz --config /etc/ranch-web-updater.toml --apply v2.0.6 --dry-run
python3 -B /opt/ranch-web/updater.pyz --config /etc/ranch-web-updater.toml --apply v2.0.7 --dry-run
```
`--version` 应显示 `ranch-web-updater 2.0.6`;`--help`、`--version` 和 `--dry-run` 均不联网、不读取 Token、不调用 Docker,dry-run 不创建文件。Python 需为 3.12+。
`--version` 应显示 `ranch-web-updater 2.0.7`;`--help`、`--version` 和 `--dry-run` 均不联网、不读取 Token、不调用 Docker,dry-run 不创建文件。Python 需为 3.12+。
2. 用户创建只授予本仓库 Contents **read** 的 fine-grained GitHub Token,用交互终端输入;值不出现在 argv、shell 历史或更新状态中:
@@ -161,12 +161,12 @@ Windows 或未安装执行器的 Docker 部署仍能检查版本,但按钮会
[web-image.yml](../../.github/workflows/web-image.yml) 仅对官方仓库的严格稳定 `v2.x.y` tag 推送 `ghcr.io/attilanet/myrzx_bot-web:v2.x.y`;校验 `ranch_web.__version__` 必须与 tag 一致,不能只改变镜像 label。PR 与手动运行只测试、构建,不推送。开发分支 push 不触发正式镜像发布,也没有 `latest` 滚动升级通道。CI 执行更新器、私有凭据和独立包回归,并在无外网容器中检查 healthcheck、非 root 数据写权限、无 Qt 和正常停止;镜像发布状态以对应 tag 的工作流结果为准。
2.0.6 验证结果统一见 [发布说明](../../analysis/RELEASE_2_0_6.md#验证)。以下命令用于更新器离线验证;历史 Windows 离线验证与 Linux 部署烟测见 [Web 运行说明](../../ranch_web/README.md#离线验证),不计入本版验收。可在无 Docker 的机器上构建临时更新器资产并打印计划;`--dry-run` 不联网、不读取凭据、不调用 Docker,也不写文件:
2.0.7 验证结果统一见 [发布说明](../../analysis/RELEASE_2_0_7.md#验证)。以下命令用于更新器离线验证;历史 Windows 离线验证与 Linux 部署烟测见 [Web 运行说明](../../ranch_web/README.md#离线验证),不计入本版验收。可在无 Docker 的机器上构建临时更新器资产并打印计划;`--dry-run` 不联网、不读取凭据、不调用 Docker,也不写文件:
```sh
python -B tools/build_web_updater.py --output test-artifacts/updater.pyz
python -B test-artifacts/updater.pyz --version
python -B test-artifacts/updater.pyz --config deploy/web/updater.example.toml --apply v2.0.6 --dry-run
python -B test-artifacts/updater.pyz --config deploy/web/updater.example.toml --apply v2.0.7 --dry-run
python -B -m unittest ranch_web.tests.test_updates ranch_web.tests.test_web_updater ranch_web.tests.test_private_updates ranch_web.tests.test_web_updater_package -v
```
+2 -2
View File
@@ -1,2 +1,2 @@
# Pull only after the v2.0.6 image publishing workflow succeeds and the image is available.
RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.6
# Pull only after the v2.0.7 image publishing workflow succeeds and the image is available.
RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.7
+34 -10
View File
@@ -9,7 +9,9 @@ from __future__ import annotations
from dataclasses import dataclass
from .cultivation import CultivationSelector
from .model import Action
from .team_availability import _exploring_ids
PATH = "monsterService/monsterPotentialLevelUpgrade"
@@ -43,6 +45,31 @@ def field(row, name, default=None):
return getattr(row, name, default)
def primary_target_reason(catalog, cultivation, snapshot, monster_id, *, primaries=None):
"""Admission for automatic resources only; saved target maps are not authority."""
mid = integer(monster_id)
mon = snapshot.monsters.get(mid) if snapshot is not None else None
if mon is None:
return f"自动培养目标 #{monster_id} 已不在角色数据中"
label = catalog.monster_label(mon)
if mon.get("process") != 3:
return f"{label} 不在牧场,暂停自动培养"
primaries = cultivation.select(snapshot) if primaries is None else primaries
primary = primaries.get(str(mon.get("typeId")))
if primary is None:
return f"{label} 尚未确认同种主培养,暂停自动培养"
if int(primary["id"]) != mid:
return (f"{label} 是同种非主培养(备选 / 重复魔物);"
f"仅主培养 #{primary['id']} 可自动喂养、赠礼和突破")
if mon.get("inExploreTeam") or mid in _exploring_ids(snapshot):
return f"{label} 主培养正在探险,暂停自动培养,不改用备选"
if mon.get("inBuild"):
return f"{label} 主培养正在建筑,暂停自动培养,不改用备选"
if mon.get("sysLock"):
return f"{label} 主培养系统锁定,暂停自动培养,不改用备选"
return ""
@dataclass(frozen=True)
class Material:
type_id: int
@@ -66,8 +93,9 @@ class Candidate:
class BreakthroughPlanner:
"""Plan PotentialPanel writes; each call returns at most one operation."""
def __init__(self, catalog):
def __init__(self, catalog, cultivation=None):
self.catalog = catalog
self.cultivation = cultivation or CultivationSelector(catalog)
self.notes = []
@staticmethod
@@ -228,18 +256,14 @@ class BreakthroughPlanner:
if not ids:
self.notes.append("未选择自动突破目标")
return None
primaries = self.cultivation.select(snapshot)
for mid in ids:
mon = snapshot.monsters.get(mid)
if not mon:
self.notes.append(f"#{mid} 已不在角色数据中")
reason = primary_target_reason(self.catalog, self.cultivation, snapshot, mid, primaries=primaries)
if reason:
self.notes.append(reason)
continue
mon = snapshot.monsters[mid]
label = self.catalog.monster_label(mon)
if mon.get("process") != 3:
self.notes.append(f"{label} 不在牧场")
continue
if mon.get("inExploreTeam") or mon.get("inBuild"):
self.notes.append(f"{label} 正在探险或建筑,暂停自动突破")
continue
level, caps, reason = self.caps(mon)
if level is None:
self.notes.append(f"{label}:{reason}")
+30 -19
View File
@@ -1,7 +1,6 @@
"""Choose a single ranch representative per species, independently of gifts."""
"""Choose a stable cultivation primary per species, independently of eligibility."""
import json
from pathlib import Path
import random
import threading
@@ -20,14 +19,11 @@ def growth_score(catalog, mon):
def quality_rank(catalog, mon):
"""Compare letter grades before using raw growth to break exact-grade ties."""
"""Compare S counts, then the equal-weight mean of all normalized growth."""
qualities = catalog.quality(mon)
if any(value is None for value in qualities):
return None
# A and B grades are compared per attribute. A raw average must never
# make AASA outrank SSAS (or turn an S-grade advantage into a B-grade one).
return (sum(value == 4 for value in qualities), sum(value == 3 for value in qualities),
sum(value == 2 for value in qualities), growth_score(catalog, mon))
return (sum(value == 4 for value in qualities), growth_score(catalog, mon))
def quality_summary(catalog, mon):
@@ -37,6 +33,8 @@ def quality_summary(catalog, mon):
class CultivationSelector:
"""Persist primary IDs in the caller's account/role-scoped choices file."""
def __init__(self, catalog, path=None):
self.catalog = catalog
self.path = Path(path) if path else None
@@ -47,17 +45,23 @@ class CultivationSelector:
self.lock = threading.RLock()
def rank(self, mon):
values = growth_values(self.catalog, mon)
"""Comparable (level, feel, S count, equal-weight normalized growth)."""
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)
*(quality_rank(self.catalog, mon) or (-1, -1)))
def select(self, snapshot):
"""Return {str(typeId): current primary row} for mature ranch monsters.
Initial selection uses rank, then the oldest ID. An existing primary
changes only for a strictly higher-level ranch monster or confirmed
removal. A saved ID still present outside the ranch blocks fallback.
"""
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))
monsters = snapshot.raw["monsters"]
ranch = [mon for mon in monsters if mon.get("process") == 3 and mon.get("typeId") is not None]
signature = (owner, tuple((int(mon["id"]), str(mon.get("typeId")), mon.get("process"), mon.get("level"), mon.get("feel"),
*(mon.get(key) for key in ("gAtk", "gDef", "gHp", "gDex"))) for mon in monsters))
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()}
@@ -72,17 +76,24 @@ class CultivationSelector:
except (OSError, ValueError, TypeError, AttributeError):
pass
self.owner = owner
# Snapshot.monsters is the complete authoritative roster. A removed
# ID may be replaced, while a present non-ranch primary stays saved.
current_ids = {int(mon["id"]) for mon in monsters}
choices = {key: mid for key, mid in self.choices.items() if mid in current_ids}
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()}
previous = next((mon for mon in members if int(mon["id"]) == choices.get(key)), None)
if previous is None and key in choices:
continue
highest_level = max(int(mon.get("level") or 1) for mon in members)
if previous is not None and int(previous.get("level") or 1) >= highest_level:
selected[key] = previous
else:
selected[key] = max(members, key=lambda mon: (self.rank(mon), -int(mon["id"])))
choices.update({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)
+61 -7
View File
@@ -27,7 +27,7 @@ from .progression import ProgressionIntent, ProgressionPlanner, ProgressionPolic
from .battle_messages import battle_message
from .maps import stages
from .exploration import ExplorePlanner, ExplorePolicy
from .breakthrough import BreakthroughPlanner
from .breakthrough import BreakthroughPlanner, primary_target_reason
def account_serial(method):
@@ -87,7 +87,7 @@ class Engine:
self.sweeper = SweepRunner(catalog, folder / "sweep_runs.json" if folder else None)
self.explore_planner = ExplorePlanner(catalog)
self.explore_policy = ExplorePolicy()
self.breakthrough_planner = BreakthroughPlanner(catalog)
self.breakthrough_planner = BreakthroughPlanner(catalog, self.cultivation)
self.automation_state_path = folder / "automation_state.json" if folder else None
self._explore_pending_last_check = 0
self._explore_pending_confirmed = False
@@ -283,9 +283,37 @@ class Engine:
self.auto = False
raise
def cultivation_target_reason(self, monster_id, *, primaries=None):
return primary_target_reason(self.catalog, self.cultivation, self.snapshot, monster_id, primaries=primaries)
def _automatic_cultivation_reason(self, action, *, primaries=None):
recipient_key = {"feed": "targetId", "gift": "monsterId", "potential": "monId", "breakthrough": "monId"}.get(action.kind)
return self.cultivation_target_reason(action.payload.get(recipient_key), primaries=primaries) if recipient_key else ""
def _admit_automatic_cultivation(self, actions):
primaries = self.cultivation.select(self.snapshot)
admitted = []
for action in actions:
reason = self._automatic_cultivation_reason(action, primaries=primaries)
if reason:
self.planner.notes.append("跳过自动操作:" + reason)
else:
admitted.append(action)
return admitted
def _skip_automatic_cultivation(self, reason):
self.last_executed = False
plans = self.plans()
self.planner.notes.append("跳过自动操作:" + reason)
return self.snapshot, plans, "跳过自动操作:" + reason
def _execute_breakthrough(self, action):
self.last_executed = False
if self._breakthrough_pending:
return self.snapshot, [], "突破请求待核对,禁止重发"
reason = self._automatic_cultivation_reason(action)
if reason:
return self._skip_automatic_cultivation(reason)
mon = self.snapshot.monsters[int(action.payload["monId"])]
attribute = action.payload.get("monsterAttr", "")
before = mon.get("p" + attribute.capitalize()) if action.kind == "potential" else mon.get("potentialLevel")
@@ -305,7 +333,14 @@ class Engine:
if not self.auto or self._progression_cancel.is_set():
self._discard_unsent_automation()
return self.snapshot, self.plans(), "突破请求尚未发送,已取消"
reason = self._automatic_cultivation_reason(action)
if reason:
# Only this newly journaled, unsent request may be discarded. An
# older pending request returned above and must retain its evidence.
self._discard_unsent_automation()
return self._skip_automatic_cultivation(reason)
try:
self.last_executed = True
response = self.client.call(action.path, deepcopy(action.payload))
if not isinstance(response, dict) or response.get("resCode", 0) not in (0, "0"):
raise ValueError("突破请求尚未确认成功")
@@ -1061,6 +1096,9 @@ class Engine:
self.last_executed = True
return self._execute_breakthrough(action)
if self.auto and action is not None:
reason = self._automatic_cultivation_reason(action)
if reason:
return self._skip_automatic_cultivation(reason)
self.last_executed = True
if action.kind == "progression":
return self._run_progression_intent(action.payload["intent"])
@@ -1146,8 +1184,14 @@ class Engine:
if not self.auto or self._progression_cancel.is_set():
return self.snapshot, plans, "策略已停止,快速操作未执行"
if action is None:
return self.snapshot, plans, {"explore": "探险", "breakthrough": "突破",
message = {"explore": "探险", "breakthrough": "突破",
"gift": "赠礼", "hatch": "孵化"}[kind] + "当前无可执行动作"
if self.planner.notes:
message += ";" + ";".join(dict.fromkeys(self.planner.notes))
return self.snapshot, plans, message
reason = self._automatic_cultivation_reason(action)
if reason:
return self._skip_automatic_cultivation(reason)
self.last_executed = True
if kind == "explore":
return self._execute_explore(action)
@@ -1298,8 +1342,7 @@ class Engine:
if self.snapshot is None or self._progression_pending():
self.pending_hatches = []
return []
if self.policy.keep_better_quality or self.policy.gift_auto_representative:
self.cultivation.select(self.snapshot)
primaries = self.cultivation.select(self.snapshot)
# One owner for commission writes; never accept the same offer through
# both the legacy planner and the full progression planner.
quests = [] if self._commission_planner_available else self.tasks.plan(self.snapshot, self.quest_policy, self.policy)
@@ -1318,18 +1361,29 @@ class Engine:
ranch = self.planner.plan(self.snapshot, policy, left)
explore = self.explore_planner.plan(self.snapshot, self.explore_policy, policy)
breakthrough_policy = SimpleNamespace(**(asdict(policy) | {"item_reserves": dict(self.quest_policy.item_reserves)}))
self.breakthrough_planner.notes = []
breakthrough = self.breakthrough_planner.plan(self.snapshot, breakthrough_policy,
targets=policy.breakthrough_targets, enabled=not self._breakthrough_pending) if policy.breakthrough_targets else None
self.planner.notes.extend(self.gift_planner.notes)
self.planner.notes.extend(self.breakthrough_planner.notes)
feed_targets = policy.feed_targets or ({str(policy.feed_target): 1} if policy.feed_target else {})
for enabled, targets in (
(policy.enabled and policy.feed, feed_targets),
(policy.gift_enabled and not policy.gift_auto_representative, policy.gift_targets),
(policy.enabled, policy.breakthrough_targets)):
if enabled:
for mid in targets:
reason = self.cultivation_target_reason(mid, primaries=primaries)
if reason:
self.planner.notes.append("跳过自动目标:" + reason)
breakthroughs = [breakthrough] if breakthrough else []
progression = [Action("progression", value(intent, "description", "推进任务"), "", {"intent": intent})
for intent in self._progression_intents if not value(intent, "block_reason") and self._intent_policy(intent).enabled]
commission = [action for action in progression if self._is_commission(action.payload["intent"])]
progression = [action for action in progression if not self._is_commission(action.payload["intent"])]
if quests and quests[0].kind == "quest_reset":
return quests + commission[:1] + daily + progression[:1] + explore + breakthroughs + gifts + ranch + sweep_actions
return commission[:1] + quests + daily + progression[:1] + explore + breakthroughs + gifts + ranch + sweep_actions
return self._admit_automatic_cultivation(quests + commission[:1] + daily + progression[:1] + explore + breakthroughs + gifts + ranch + sweep_actions)
return self._admit_automatic_cultivation(commission[:1] + quests + daily + progression[:1] + explore + breakthroughs + gifts + ranch + sweep_actions)
@account_serial
def claim_daily_entry(self, entry):
+10 -4
View File
@@ -2,6 +2,7 @@
import math
from .model import Action, seconds
from .cultivation import CultivationSelector
from .team_availability import _exploring_ids
def item_reserve(item_type, ranch, quests):
@@ -40,11 +41,16 @@ class GiftPlanner:
mon.update(feel=entry["feel"], giftTime=entry["giftTime"])
def candidates(self, snapshot, policy):
# Select identity before checking availability; a busy primary must
# never cause its quality backup to receive cultivation resources.
primaries = self.cultivation.select(snapshot)
exploring = _exploring_ids(snapshot)
available = {int(mon["id"]): mon for mon in primaries.values()
if not mon.get("inExploreTeam") and not mon.get("inBuild") and int(mon["id"]) not in exploring}
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]
return sorted(available.values(), key=lambda mon: self.cultivation.rank(mon), reverse=True)
return [available[int(key)] for key, _ in sorted(policy.gift_targets.items(), key=lambda pair: pair[1])
if int(key) in available]
def target(self, snapshot, policy):
for mon in self.candidates(snapshot, policy):
+217 -150
View File
@@ -6,6 +6,7 @@ import math
from pathlib import Path
import time
from .cultivation import CultivationSelector, growth_score, quality_rank, quality_summary
from .team_availability import _exploring_ids
WIKI = "https://wiki.biligame.com/myrzx/魔物收益表"
@@ -369,57 +370,70 @@ class Planner:
self.retained = set()
self.retention_reasons = {}
self.representatives = {}
self.backups = {}
self.retention_owner = None
self.dispatch_extras = set()
self.preparing_retention = False
self.retention_signature = None
self.tp_feed_targets = set()
self.food_protection = {}
def protected(self, mon, snapshot, policy):
self.ensure_retention(snapshot, policy)
return bool(self.protection_reason(mon, snapshot, policy))
def ensure_retention(self, snapshot, policy):
if not policy.manual_eggs:
if self.preparing_retention:
return
signature = (repr(snapshot.raw.get("monsters")), repr(snapshot.raw.get("teams")),
signature = (str(snapshot.raw["master"]["id"]),
repr(snapshot.raw.get("monsters")), repr(snapshot.raw.get("teams")),
repr(snapshot.raw.get("exploreTeams")),
repr((policy.manual_eggs, policy.egg_rules, policy.keep_better_quality,
policy.gift_auto_representative, policy.protect_star, policy.protect_quality,
policy.feed_target, policy.feed_targets, policy.breakthrough_targets, policy.reserved_types)))
policy.feed_target, policy.feed_targets, policy.gift_targets,
policy.breakthrough_targets, policy.reserved_types)))
if signature != self.retention_signature:
self.prepare_retention(snapshot, policy)
self.retention_signature = signature
def protection_reason(self, mon, snapshot, policy):
@staticmethod
def species_rule(mon, policy):
rule = policy.egg_rules.get(str(mon.get("typeId")), {}) if policy.manual_eggs else {}
return rule if rule.get("enabled") else {}
def hard_protection_reason(self, mon, snapshot, policy):
"""Explicit reservations and incomplete data are independent of slot limits."""
row = self.catalog.monster(mon.get("typeId"))
qualities = self.catalog.quality(mon)
legacy_protection = not self.species_rule(mon, policy)
for condition, reason in ((not row, "魔物资料未知"), (int(mon["id"]) in snapshot.team_ids, "在队魔物"),
(mon.get("lock"), "已锁定"), (mon.get("sysLock"), "系统锁定"), (mon.get("entangle"), "羁绊魔物"),
(mon.get("inExploreTeam"), "正在探索"), (mon.get("inBuild"), "正在建筑中"),
(mon.get("inExploreTeam") or int(mon["id"]) in _exploring_ids(snapshot), "正在探索"),
(mon.get("inBuild"), "正在建筑中"),
(any(mon.get(f"equip{i}", 0) for i in range(1, 6)), "携带装备"),
(int(mon["id"]) == policy.feed_target or str(mon["id"]) in policy.feed_targets, "已选为喂养目标"),
(str(mon["id"]) in policy.breakthrough_targets, "已选为自动突破目标"),
(legacy_protection and (int(mon["id"]) == policy.feed_target or str(mon["id"]) in policy.feed_targets), "已选为喂养目标"),
(legacy_protection and str(mon["id"]) in policy.gift_targets, "已选为赠礼目标"),
(legacy_protection and str(mon["id"]) in policy.breakthrough_targets, "已选为自动突破目标"),
(str(mon.get("typeId")) in {str(t) for t in policy.reserved_types}, "保留种类或委托保留"),
(row.get("star", 0) >= policy.protect_star, f"{row.get('star', '?')}星达到保留星级{policy.protect_star}"),
(legacy_protection and row.get("star", 0) >= policy.protect_star, f"{row.get('star', '?')}星达到保留星级{policy.protect_star}"),
(any(q is None for q in qualities), "资质尚未确定 / 未同步")):
if condition:
return reason
return ""
def protection_reason(self, mon, snapshot, policy):
self.ensure_retention(snapshot, policy)
reason = self.hard_protection_reason(mon, snapshot, policy)
if reason:
return reason
if int(mon["id"]) in self.retained:
return self.retention_reasons[int(mon["id"])]
# Enabled species use fixed primary/backup slots. Automatic grade
# thresholds and legacy keep_count must not protect every duplicate.
if self.species_rule(mon, policy):
return ""
qualities = self.catalog.quality(mon)
quality = math.ceil(sum(qualities) / 4)
if (policy.keep_better_quality or policy.gift_auto_representative) and not policy.manual_eggs:
representative = (self.representatives if policy.manual_eggs else self.cultivation.select(snapshot)).get(str(mon.get("typeId")))
if policy.gift_auto_representative and representative and int(representative["id"]) == int(mon["id"]):
return "同种魔物的唯一培养代表(等级、好感、资质优先)"
if policy.keep_better_quality and not self.preparing_retention:
if representative is None:
return "牧场尚无同种魔物,保留首次获得的魔物"
baseline, candidate = quality_rank(self.catalog, representative), quality_rank(self.catalog, mon)
if baseline is None:
return "同种培养代表的资质尚未同步,暂时保留"
if candidate is not None and candidate > baseline:
return (f"资质优于同种培养代表 #{representative['id']}"
f"({quality_summary(self.catalog, mon)} / S项{candidate[0]} > "
f"{quality_summary(self.catalog, representative)} / S项{baseline[0]})")
if policy.protect_quality == 6:
return "攻/防/生命/敏捷四项资质全S(4S)" if all(q == 4 for q in qualities) else ""
if quality >= policy.protect_quality:
@@ -427,100 +441,82 @@ class Planner:
return ""
def prepare_retention(self, snapshot, policy):
"""Allocate each species quota once for all ranches and this hatch batch."""
"""One primary and one strictly better backup across ranches/incubators."""
owner = str(snapshot.raw["master"]["id"])
previous_backups = self.backups if self.retention_owner == owner else {}
self.retention_owner = owner
self.backups, self.dispatch_extras = {}, set()
self.retained, self.retention_reasons, self.representatives = set(), {}, {}
self.retention_signature = None
if not policy.manual_eggs:
return
self.preparing_retention = True
try:
for mon in snapshot.raw["monsters"]:
if mon.get("process") == 3:
reason = self.protection_reason(mon, snapshot, policy)
if reason:
self.retained.add(int(mon["id"]))
self.retention_reasons[int(mon["id"])] = reason
finally:
self.preparing_retention = False
self.representatives = self.cultivation.select(snapshot)
self.representatives = dict(self.cultivation.select(snapshot))
groups = {}
for mon in snapshot.raw["monsters"]:
if mon.get("process") in (2, 3) and int(mon.get("mode") or 0) == 2:
if mon.get("process") == 3 or mon.get("process") == 2 and int(mon.get("mode") or 0) == 2:
groups.setdefault(str(mon.get("typeId")), []).append(mon)
for key, rule in policy.egg_rules.items():
if not rule.get("enabled"):
for key, members in groups.items():
mandatory = bool(self.species_rule(members[0], policy))
if not mandatory and not (not policy.manual_eggs and
(policy.keep_better_quality or policy.gift_auto_representative)):
continue
members = groups.get(key, [])
representative = self.representatives.get(key)
if representative is None and members:
representative = min(members, key=lambda row: (quality_rank(self.catalog, row) is None,
tuple(-value for value in (quality_rank(self.catalog, row) or ())), int(row["id"])))
quota = int(rule.get("keep_count", 1))
occupied = sum(row.get("process") == 3 and int(row["id"]) in self.retained for row in members)
if quota > 0 and representative is not None and representative.get("process") == 3 and occupied < quota:
mid = int(representative["id"])
already_retained = mid in self.retained
primary = self.representatives.get(key)
if primary is None:
saved_id = getattr(self.cultivation, "choices", {}).get(key)
saved = snapshot.monsters.get(saved_id)
# A saved primary that is still in the roster can be temporarily
# unavailable. Only confirmed removal permits a replacement.
primary = saved if saved is not None and str(saved.get("typeId")) == key else min(
members, key=lambda row: int(row["id"]))
self.representatives[key] = primary
primary_id = int(primary["id"])
self.retained.add(primary_id)
self.retention_reasons[primary_id] = ("牧场尚无同种魔物,保留首次成熟的主培养魔物"
if primary.get("process") != 3 else "同种稳定主培养代表(等级、好感、资质优先)")
baseline = quality_rank(self.catalog, primary)
candidates = [(quality_rank(self.catalog, mon), mon) for mon in members
if int(mon["id"]) != primary_id]
if baseline is None:
for _, mon in candidates:
mid = int(mon["id"])
self.retained.add(mid)
self.retention_reasons[mid] = f"同种稳定培养代表,牧场保留数量 1 / {quota}"
occupied += int(representative.get("process") == 3 and not already_retained)
ranch = [row for row in members if row.get("process") == 3 and int(row["id"]) not in self.retained]
ranch.sort(key=lambda row: (quality_rank(self.catalog, row) is None,
tuple(-value for value in (quality_rank(self.catalog, row) or ())), int(row["id"])))
used = occupied
quality_baseline = [quality_rank(self.catalog, row) for row in members
if row.get("process") == 3 and int(row["id"]) in self.retained]
quality_baseline = [value for value in quality_baseline if value is not None]
for row in ranch:
if used >= quota:
break
used += 1
self.retained.add(int(row["id"]))
self.retention_reasons[int(row["id"])] = f"同种牧场保留数量 {used} / {quota}"
rank = quality_rank(self.catalog, row)
if rank is not None:
quality_baseline.append(rank)
incubator = [row for row in members if row.get("process") == 2 and int(row["id"]) not in self.retained]
incubator.sort(key=lambda row: (quality_rank(self.catalog, row) is None,
tuple(-value for value in (quality_rank(self.catalog, row) or ())), int(row["id"])))
for row in incubator:
if used >= quota:
break
used += 1
self.retained.add(int(row["id"]))
self.retention_reasons[int(row["id"])] = f"同种牧场及培育室保留数量 {used} / {quota}"
rank = quality_rank(self.catalog, row)
if rank is not None:
quality_baseline.append(rank)
# Compare with the best retained ranch quality, not repeatedly
# with an inferior locked monster. Select at most one improvement
# per snapshot, including the newly collected batch as one group.
if policy.keep_better_quality and quality_baseline:
baseline = max(quality_baseline)
candidates = [(quality_rank(self.catalog, row), row) for row in members
if int(row["id"]) not in self.retained]
candidates = [(rank, row) for rank, row in candidates if rank is not None and rank > baseline]
if candidates:
rank, row = min(candidates, key=lambda pair: (-pair[0][0], -pair[0][1], -pair[0][2], -pair[0][3], int(pair[1]["id"])))
self.retained.add(int(row["id"]))
self.retention_reasons[int(row["id"])] = (
f"额外保留更优资质 {quality_summary(self.catalog, row)} / S项{rank[0]},"
f"牧场已保留最高资质 S项{baseline[0]}")
# If the only mature monster is still incubating, it becomes the
# representative upon collection rather than being disposed first.
if quota > 0 and not any(int(row["id"]) in self.retained for row in members) and members:
row = members[0]
self.retained.add(int(row["id"]))
self.retention_reasons[int(row["id"])] = f"同种本批培养代表,牧场保留数量 1 / {quota}"
self.retention_reasons[mid] = f"同种主培养代表 #{primary_id} 当前不可用或资质尚未同步,暂时保护"
continue
if mandatory or policy.keep_better_quality:
better = [(rank, mon) for rank, mon in candidates if rank is not None and rank > baseline]
if better:
previous_id = int(previous_backups.get(key, {}).get("id", 0))
rank, backup = min(better, key=lambda pair: (
tuple(-value for value in pair[0]), pair[1].get("process") != 3,
int(pair[1]["id"]) != previous_id, int(pair[1]["id"])))
mid = int(backup["id"])
self.backups[key] = backup
self.retained.add(mid)
self.retention_reasons[mid] = (f"唯一资质备用,优于同种培养代表 #{primary_id}:"
f"{quality_summary(self.catalog, backup)} / S项{rank[0]};不喂养、不赠礼")
for rank, mon in candidates:
mid = int(mon["id"])
if mid in self.retained:
continue
reason = self.hard_protection_reason(mon, snapshot, policy)
if reason:
self.retained.add(mid)
self.retention_reasons[mid] = "同种额外魔物受保护:" + reason
elif mandatory and (rank is not None and rank >= baseline
or mid == int(previous_backups.get(key, {}).get("id", 0))):
self.dispatch_extras.add(mid)
def disposition(self, mon, snapshot, policy):
if self.protected(mon, snapshot, policy):
return "keep"
if policy.manual_eggs:
rule = policy.egg_rules.get(str(mon["typeId"]), {})
return rule.get("action", "keep") if rule.get("enabled") else "keep"
if not rule.get("enabled"):
return "keep"
# Only recorded hatch ownership authorizes using an old monster as
# food. Enabled-species cleanup separately authorizes dispatch.
if (int(mon["id"]) in self.dispatch_extras or rule.get("action") != "feed"
or int(mon["id"]) not in self.managed):
return "sell"
return "feed"
if policy.strategy == "keep":
return "keep"
if policy.strategy in ("gold", "experience"):
@@ -536,6 +532,10 @@ class Planner:
target = snapshot.monsters.get(mid)
if not target or target.get("process") != 3:
continue
blocked = self.primary_target_reason(target, snapshot)
if blocked:
reason = blocked
continue
cap = self.catalog.max_level(target)
if cap is None:
reason = "目标突破上限未知,暂停喂养"
@@ -550,6 +550,18 @@ class Planner:
return target, reason
return None, reason
def primary_target_reason(self, target, snapshot):
"""A backup can be protected as food without being a cultivation target."""
primary = self.cultivation.select(snapshot).get(str(target.get("typeId")))
if primary is None:
return "该种主培养魔物尚未收取到牧场,暂停喂养"
if int(primary["id"]) != int(target["id"]):
return f"目标 #{target['id']} 不是同种主培养代表 #{primary['id']},保留原勾选并暂停该目标"
if (target.get("process") != 3 or target.get("inExploreTeam") or int(target["id"]) in _exploring_ids(snapshot)
or target.get("inBuild") or target.get("sysLock")):
return f"同种主培养代表 #{target['id']} 当前不可用,暂停喂养"
return ""
def feed_status(self, snapshot, policy):
target, reason = self.feeding_target(snapshot, policy)
return target is not None, reason
@@ -584,44 +596,35 @@ class Planner:
return max(0, thresholds[4] - int(target.get("tpExp")))
def same_species_feeding_target(self, mon, snapshot, policy, exclude=()):
"""Prefer an unfinished same-species TP target; never consume a representative."""
"""Feed only the primary; its caps never authorize a duplicate target."""
self.ensure_retention(snapshot, policy)
if mon.get("process") != 3:
return None, "素材尚未收取到牧场"
excluded = {int(mid) for mid in exclude} | {int(mon["id"])}
candidates = [row for row in snapshot.raw["monsters"] if row.get("process") == 3
and str(row.get("typeId")) == str(mon.get("typeId"))
and int(row["id"]) != int(mon["id"])
and not self.food_protection.get(int(row["id"]))
and (quality_rank(self.catalog, mon) is None or quality_rank(self.catalog, row) is not None
and quality_rank(self.catalog, row) >= quality_rank(self.catalog, mon))
and (int(row["id"]) in self.managed or self.protected(row, snapshot, policy))]
candidates.sort(key=lambda row: (int(policy.feed_targets.get(str(row["id"]), 9999)),
int(policy.breakthrough_targets.get(str(row["id"]), 9999)), -int(row.get("level") or 1), int(row["id"])))
unknown = False
for target in candidates:
target = self.cultivation.select(snapshot).get(str(mon.get("typeId")))
if target is None:
return None, "同种主培养魔物尚未收取到牧场,暂停喂养"
blocked = self.primary_target_reason(target, snapshot)
if blocked:
return None, blocked
if int(mon["id"]) == int(target["id"]) or self.protected(mon, snapshot, policy):
return None, "主培养魔物、资质备用或受保护魔物不能作为喂养素材"
if policy.feed_targets or policy.feed_target:
selected = {int(key) for key in policy.feed_targets} if policy.feed_targets else {policy.feed_target}
if int(target["id"]) not in selected:
return None, f"同种主培养代表 #{target['id']} 未勾选为喂养目标,保留原勾选"
remaining = self.tp_feeding_remaining(target)
if remaining is None:
unknown = True
continue
# TP food works even at the ordinary experience cap. Do not use
# potentialLevel here: it controls the separate material breakthrough.
return None, "缺少game_setting.tpExp累计门槛,暂停同种突破喂养"
# TP and ordinary experience have independent caps. Neither cap
# permits falling through to another member of this species.
if remaining > 0:
self.tp_feed_targets.add(int(target["id"]))
return target, f"优先同种突破喂养 #{target['id']}(tpLevel {int(target.get('tpLevel') or 0)} / 4)"
return target, f"优先同种主培养突破喂养 #{target['id']}(tpLevel {int(target.get('tpLevel') or 0)} / 4)"
cap = self.catalog.max_level(target)
if remaining == 0 and cap is not None and int(target.get("level") or 1) < cap and self.catalog.feed_remaining(target, cap) != 0:
if cap is not None and int(target.get("level") or 1) < cap and self.catalog.feed_remaining(target, cap) != 0:
self.tp_feed_targets.add(int(target["id"]))
return target, f"同种突破已满,继续普通经验喂养 #{target['id']}"
if unknown:
return None, "缺少game_setting.tpExp累计门槛,暂停同种突破喂养"
ordinary = [target for target in candidates if self.tp_feeding_remaining(target) == 0
and self.catalog.max_level(target) is not None and int(target.get("level") or 1) < self.catalog.max_level(target)
and self.catalog.feed_remaining(target, self.catalog.max_level(target)) != 0]
if ordinary:
target = ordinary[0]
self.tp_feed_targets.add(int(target["id"]))
return target, f"同种突破已满,继续普通经验喂养 #{target['id']}"
return None, "同种魔物均已完成突破,不继续消耗同种素材"
return None, f"同种主培养代表 #{target['id']} 突破及当前经验已满或上限未知,暂停喂养"
def is_same_species_tp_feed(self, target, food):
return self.tp_food_value(target, food) > 0 and (self.tp_feeding_remaining(target) or 0) > 0
@@ -732,6 +735,11 @@ class Planner:
self.notes.append("请到“背包魔物蛋”勾选要孵化的蛋,并设置优先级和孵出后的去向")
return []
actions = []
ranch_counts = {}
for mon in snapshot.raw["monsters"]:
if mon.get("process") == 3:
key = str(mon.get("typeId"))
ranch_counts[key] = ranch_counts.get(key, 0) + 1
free_rooms = {}
for room in snapshot.raw["rooms"]:
rid = int(room["id"])
@@ -742,7 +750,8 @@ class Planner:
free_rooms[rid] = max(0, capacity - used)
for mon in snapshot.raw["monsters"]:
mid = int(mon["id"])
if mid not in self.managed or mon.get("process") not in (2, 3):
rule = self.species_rule(mon, policy)
if (mid not in self.managed and not rule) or mon.get("process") not in (2, 3):
continue
if policy.manual_eggs and not policy.egg_rules.get(str(mon["typeId"]), {}).get("enabled"):
self.statuses[mid] = "该魔物未启用孵蛋规则"
@@ -762,15 +771,33 @@ class Planner:
if disposition == "sell" and not policy.dispatch or disposition == "feed" and not policy.feed:
reason = "自动派遣开关已关闭" if disposition == "sell" else "自动喂养开关已关闭"
disposition = "keep"
if disposition == "keep" and self.hard_protection_reason(mon, snapshot, policy):
reason = "受保护:" + reason
self.statuses[mid] = "保留:" + reason if disposition == "keep" else "待派遣" if disposition == "sell" else "待喂养"
if disposition == "sell":
# MonsterCenter also routes mature incubator monsters through
# NetMonster.sellMonsters, whose active parameter is plural.
actions.append(Action("sell", f"派遣 {name} #{mid}", "monsterService/monsterSell", {"monsterIds": [mid]}))
elif mon.get("process") == 2 and policy.collect:
key = str(mon.get("typeId"))
primary = self.representatives.get(key)
if rule and primary and primary.get("process") != 3 and mid != int(primary["id"]):
self.statuses[mid] = f"等待先收取首次主培养魔物 #{primary['id']},刷新后再处理备用"
self.notes.append(f"{name}:" + self.statuses[mid])
continue
if rule and ranch_counts.get(key, 0) >= 2:
if disposition == "feed" and policy.dispatch:
actions.append(Action("sell", f"同种已达两只,派遣多余素材 {name} #{mid}",
"monsterService/monsterSell", {"monsterIds": [mid]}))
self.statuses[mid] = "同种牧场已达两只,待派遣多余素材"
else:
self.statuses[mid] = "等待收取:同种牧场已达两只,需先派遣多余魔物;受保护魔物不自动解除保护"
self.notes.append(f"{name}:" + self.statuses[mid])
continue
room = next((rid for rid, free in free_rooms.items() if free > 0), None)
if room is not None:
free_rooms[room] -= 1
ranch_counts[key] = ranch_counts.get(key, 0) + 1
actions.append(Action("collect", f"收取 {name} #{mid} → 牧场 {room}", "stackService/stackTransferMonster", {"datas": [{"monsterId": [mid], "roomId": room}]}))
else:
self.notes.append(f"{name} 等待收取:牧场没有空位")
@@ -785,6 +812,10 @@ class Planner:
actions.append(Action("feed", f"{name} #{mid} → 喂养 #{target['id']}", "monsterService/monsterIntensify", {"targetId": int(target["id"]), "foods": [mid]}))
else:
self.notes.append("暂停喂养:" + reason)
self.statuses[mid] = "暂停喂养:" + reason
if rule and policy.dispatch:
actions.append(Action("sell", f"主培养暂不可喂养,派遣多余素材 {name} #{mid}",
"monsterService/monsterSell", {"monsterIds": [mid]}))
elif disposition == "keep":
self.notes.append(f"{name} 已保留:{reason}")
if actions:
@@ -828,6 +859,13 @@ class Planner:
def batch_actions(self, actions, snapshot, policy):
monsters = snapshot.monsters
collects = [a for a in actions if a.kind == "collect"]
species_dispatches = [a for a in actions if a.kind == "sell" and any(
mid in monsters and self.species_rule(monsters[mid], policy)
for mid in a.payload["monsterIds"])]
if collects and species_dispatches:
# Dispose of rejected duplicates before admitting another monster.
# The next plan must use a refreshed snapshot after this write.
return [a for a in actions if a.kind == "sell"]
merged_collect = None
if collects:
rooms = {}
@@ -845,21 +883,50 @@ class Planner:
feeds = [a for a in actions if a.kind == "feed"]
if not feeds:
return ([merged_collect] if merged_collect else []) + actions
target_id = feeds[0].payload["targetId"]
target = monsters[target_id]
feeds = [action for action in feeds if action.payload["targetId"] == target_id
and all(mid != target_id and mid in self.managed and not self.protected(monsters[mid], snapshot, policy)
for mid in action.payload["foods"])]
if not feeds:
return ([merged_collect] if merged_collect else [])
stop_level = self.catalog.max_level(target)
need = self.catalog.feed_remaining(target, stop_level)
same_species = target_id in self.tp_feed_targets and all(self.is_same_species_tp_feed(target, monsters[mid])
for action in feeds if action.payload["targetId"] == target_id for mid in action.payload["foods"])
tp_need = self.tp_feeding_remaining(target) if same_species else 0
ids, experience, tp_experience = [], 0, 0
feeding = self._batch_feeding(feeds, snapshot, policy)
return feeding + [a for a in actions if a.kind != "feed"]
def _batch_feeding(self, feeds, snapshot, policy):
"""Revalidate the primary and every material at the final batch boundary."""
if not policy.enabled or not policy.feed:
return []
self.ensure_retention(snapshot, policy)
monsters = snapshot.monsters
selected, selected_reason = self.feeding_target(snapshot, policy) if policy.feed_targets or policy.feed_target else (None, "")
valid = []
for action in feeds:
for mid in action.payload["foods"]:
target_id = int(action.payload["targetId"])
target = monsters.get(target_id)
reason = self.primary_target_reason(target, snapshot) if target else "喂养目标已不存在"
if not reason and (policy.feed_targets or policy.feed_target) and (selected is None or int(selected["id"]) != target_id):
reason = selected_reason or "目标未勾选为喂养目标"
if reason:
self.notes.append("暂停喂养:" + reason)
continue
foods = [int(mid) for mid in action.payload["foods"] if int(mid) != target_id
and int(mid) in self.managed and int(mid) in monsters
and monsters[int(mid)].get("process") == 3
and not self.protected(monsters[int(mid)], snapshot, policy)
and int(mid) not in self.dispatch_extras]
if foods:
valid.append((target_id, foods))
if not valid:
return []
target_id = valid[0][0]
target = monsters[target_id]
stop_level = self.catalog.max_level(target)
need = self.catalog.feed_remaining(target, stop_level) if stop_level is not None else None
same_species = target_id in self.tp_feed_targets and all(self.is_same_species_tp_feed(target, monsters[mid])
for mid_target, foods in valid if mid_target == target_id for mid in foods)
tp_need = self.tp_feeding_remaining(target) if same_species else 0
if not same_species and (need is None or need == 0 or int(target.get("level") or 1) >= stop_level):
self.notes.append(f"暂停喂养:主培养目标 #{target_id} 当前经验已满或突破上限未知")
return []
ids, experience, tp_experience = [], 0, 0
for mid_target, food_ids in valid:
if mid_target != target_id:
continue
for mid in food_ids:
if mid in ids or mid == target_id:
continue
ids.append(mid)
@@ -872,6 +939,6 @@ class Planner:
label = self.catalog.monster_label(target)
foods = "、".join(self.catalog.monster_label(monsters[mid]) for mid in ids)
if not ids:
return ([merged_collect] if merged_collect else []) + [a for a in actions if a not in feeds]
return []
merged = Action("feed", f"喂养 {label} ← {len(ids)} 只素材:{foods}(经验 {experience})", "monsterService/monsterIntensify", {"targetId": target_id, "foods": ids})
return ([merged_collect] if merged_collect else []) + [merged] + [a for a in actions if a not in feeds]
return [merged]
+9 -4
View File
@@ -252,6 +252,10 @@ class AutomationTests(unittest.TestCase):
def test_encrypted_http_buy_hatch_mature_dispatch_and_balance(self):
state = copy.deepcopy(self.snapshot.raw)
state["stacks"][0]["monsterId"] = -1
state["monsters"] = [{"id": 900, "typeId": 1001010, "process": 3, "mode": 2,
"level": 20, "roomId": 1, "lock": 0,
**{"g" + stat.capitalize(): self.catalog.monster(1001010)[stat + "_grow_min"]
for stat in ("atk", "def", "hp", "dex")}}]
initial_money = state["master"]["money"]
calls, catalog = [], self.catalog
with workspace_temp() as folder:
@@ -274,13 +278,13 @@ class AutomationTests(unittest.TestCase):
mon = {"id": 101, "typeId": 1001010, "mode": 0, "process": 2,
"timeStart": time.time() * 1000, "level": 1}
mon.update({"g" + s.capitalize(): catalog.monster(1001010)[s + "_grow_min"] for s in ("atk", "def", "hp", "dex")})
state["monsters"] = [mon]
state["monsters"].append(mon)
state["stacks"][0]["monsterId"] = 101
elif name == "stackCheckProcess":
state["monsters"][0]["mode"] = 2
next(mon for mon in state["monsters"] if mon["id"] == 101)["mode"] = 2
elif name == "monsterSell":
assert body["monsterIds"] == [101]
state["monsters"] = []
state["monsters"] = [mon for mon in state["monsters"] if mon["id"] != 101]
state["stacks"][0]["monsterId"] = -1
state["master"]["money"] += 150
elif name != "masterQueryDetail":
@@ -310,10 +314,11 @@ class AutomationTests(unittest.TestCase):
self.assertEqual(state["master"]["money"], initial_money - 1000)
self.assertIn("共 11 枚", engine.last_draw)
engine.poll() # Hatch, re-read, wait.
state["monsters"][0]["timeStart"] = (time.time() - 601) * 1000
next(mon for mon in state["monsters"] if mon["id"] == 101)["timeStart"] = (time.time() - 601) * 1000
snapshot, _, _ = engine.poll() # Settle growth, dispatch, re-read.
self.assertEqual(snapshot.raw["master"]["money"], initial_money - 850)
self.assertEqual(snapshot.raw["stacks"][0]["monsterId"], -1)
self.assertEqual(set(snapshot.monsters), {900})
self.assertEqual([n for n, _ in calls if n != "masterQueryDetail"],
["gachaGetEggs", "stackAddMonster", "stackCheckProcess", "monsterSell"])
engine.poll()
+10 -5
View File
@@ -36,12 +36,17 @@ class BatchFeedingTests(unittest.TestCase):
target["level"] = 20
self.assertFalse(any(a.kind == "feed" for a in self.planner.plan(self.snapshot, self.policy)))
def test_full_first_target_advances_to_next_priority(self):
def test_full_primary_skips_duplicate_and_advances_to_different_species_priority(self):
first = self.snapshot.monsters[900]
first.update(level=20, potentialLevel=2)
self.snapshot.raw["monsters"].append(copy.deepcopy(first) | {"id": 901, "level": 1, "exp": 0})
self.policy.feed_targets = {"900": 1, "901": 2}
self.assertEqual(self.planner.plan(self.snapshot, self.policy)[0].payload["targetId"], 901)
self.snapshot.raw["monsters"].extend([
copy.deepcopy(first) | {"id": 901, "level": 1, "exp": 0},
copy.deepcopy(first) | {"id": 902, "typeId": 1002010, "level": 1, "exp": 0},
])
self.policy.feed_targets = {"900": 1, "901": 2, "902": 3}
self.assertEqual(self.planner.plan(self.snapshot, self.policy)[0].payload["targetId"], 902)
del self.policy.feed_targets["902"]
self.assertFalse(any(a.kind == "feed" for a in self.planner.plan(self.snapshot, self.policy)))
def test_priority_target_uses_current_cap_instead_of_legacy_stop_level(self):
target = self.snapshot.monsters[900]
@@ -56,7 +61,7 @@ class BatchFeedingTests(unittest.TestCase):
first.update(level=19, potentialLevel=2, exp=self.catalog.data["monster_level"]["20"])
self.snapshot.raw["monsters"].extend([
copy.deepcopy(first) | {"id": 901, "potentialLevel": None},
copy.deepcopy(first) | {"id": 902, "level": 1, "exp": 0},
copy.deepcopy(first) | {"id": 902, "typeId": 1002010, "level": 1, "exp": 0},
])
self.policy.feed_targets = {"902": 3, "901": 2, "900": 1}
self.assertEqual(self.planner.plan(self.snapshot, self.policy)[0].payload["targetId"], 902)
+5 -1
View File
@@ -117,8 +117,12 @@ class BreakthroughTests(unittest.TestCase):
def test_independent_targets_replace_feed_targets_and_empty_is_empty(self):
other = copy.deepcopy(self.snapshot.monsters[900])
other["id"] = 901
row = self.catalog.monster(1003010)
caps = self.catalog.data["potential_info"]["potential"][str(row["job"])][str(row["star"])]
other.update(id=901, typeId=1003010,
**{"p" + stat.capitalize(): caps[stat] for stat in ("atk", "def", "hp", "dex")})
self.snapshot.raw["monsters"].append(other)
self.assertEqual(self.planner.plan(self.snapshot, self.policy).payload["monId"], 900)
action = self.planner.plan(self.snapshot, self.policy, targets={"901": 1})
self.assertEqual(action.payload["monId"], 901)
self.assertIsNone(self.planner.plan(self.snapshot, self.policy, targets={}))
+38 -14
View File
@@ -55,20 +55,33 @@ class CultivationTests(unittest.TestCase):
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):
def test_ties_preserve_older_ranch_member_across_refresh_restart_and_role_change(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(selector.select(self.snapshot)["1001010"]["id"], 1)
self.snapshot.raw["monsters"].reverse()
self.assertEqual(selector.select(self.snapshot)["1001010"]["id"], 1)
self.assertEqual(CultivationSelector(self.catalog, path).select(self.snapshot)["1001010"]["id"], 1)
self.snapshot.raw["master"]["id"] += 1
self.snapshot.raw["monsters"] = [monster(self.catalog, 12), monster(self.catalog, 11)]
self.assertEqual(CultivationSelector(self.catalog, path).select(self.snapshot)["1001010"]["id"], 11)
def test_present_non_ranch_primary_holds_but_confirmed_absence_promotes_once(self):
primary, duplicate = monster(self.catalog, 1, level=20), monster(self.catalog, 2, level=10)
self.snapshot.raw["monsters"] = [primary, duplicate]
with workspace_temp() as folder:
path = folder / "choices.json"
selector = CultivationSelector(self.catalog, path)
self.assertEqual(selector.select(self.snapshot)["1001010"]["id"], 1)
primary["process"] = 2
self.assertNotIn("1001010", selector.select(self.snapshot))
self.assertEqual(selector.choices["1001010"], 1)
self.assertNotIn("1001010", CultivationSelector(self.catalog, path).select(self.snapshot))
self.snapshot.raw["monsters"].remove(primary)
self.assertEqual(selector.select(self.snapshot)["1001010"]["id"], 2)
self.assertEqual(CultivationSelector(self.catalog, path).select(self.snapshot)["1001010"]["id"], 2)
def test_cached_selection_uses_current_cooldown_and_bond_cap(self):
self.snapshot.raw["monsters"] = [monster(self.catalog, 1)]
@@ -80,17 +93,24 @@ class CultivationTests(unittest.TestCase):
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):
def test_better_backup_is_mandatory_despite_legacy_flags_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)
policy = Policy(manual_eggs=True, protect_star=6, protect_quality=5,
gift_auto_representative=False, keep_better_quality=False,
egg_rules={"1001010": asdict(EggRule(enabled=True, action="sell", keep_count=1))})
for keep_better in (False, True):
for keep_count in (0, 1, 4):
with self.subTest(keep_better=keep_better, keep_count=keep_count):
policy.keep_better_quality = keep_better
policy.egg_rules["1001010"]["keep_count"] = keep_count
self.assertEqual(planner.disposition(representative, self.snapshot, policy), "keep")
self.assertEqual(planner.disposition(hatched, self.snapshot, policy), "keep")
self.assertIn("同种培养代表 #1", planner.protection_reason(hatched, self.snapshot, policy))
self.assertEqual(planner.retained, {1, 2})
policy.keep_better_quality = False
self.assertEqual(planner.disposition(hatched, self.snapshot, policy), "sell")
policy.keep_better_quality = True
policy.egg_rules["1001010"]["keep_count"] = 1
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")
@@ -146,6 +166,10 @@ class CultivationTests(unittest.TestCase):
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)
self.assertGreater(quality_rank(self.catalog, graded_monster(self.catalog, 2, "SCCC")),
quality_rank(self.catalog, graded_monster(self.catalog, 3, "AAAC")))
self.assertGreater(quality_rank(self.catalog, graded_monster(self.catalog, 4, "SSBB")),
quality_rank(self.catalog, graded_monster(self.catalog, 5, "SSAC")))
class CultivationGuiTests(unittest.TestCase):
@@ -9,6 +9,7 @@ class GiftTargetSelectionTests(unittest.TestCase):
def setUp(self):
self.catalog = Catalog()
self.snapshot = gift_snapshot(self.catalog)
self.snapshot.raw["monsters"][0]["level"] += 1
self.planner = GiftPlanner(self.catalog)
self.representative = next(iter(self.planner.cultivation.select(self.snapshot).values()))
self.manual_target = next(mon for mon in self.snapshot.raw["monsters"]
@@ -27,13 +28,20 @@ class GiftTargetSelectionTests(unittest.TestCase):
self.assertEqual([action.payload["monsterId"] for action in self.planner.plan(self.snapshot, policy)],
[self.representative["id"]])
def test_manual_mode_uses_gift_targets_instead_of_representative(self):
def test_manual_mode_requires_the_primary_to_be_explicitly_checked(self):
policy = self.policy()
self.assertEqual(self.planner.candidates(self.snapshot, policy), [])
self.assertEqual(self.planner.plan(self.snapshot, policy), [])
policy.gift_targets[str(self.representative["id"])] = 2
self.assertEqual([mon["id"] for mon in self.planner.candidates(self.snapshot, policy)],
[self.manual_target["id"]])
[self.representative["id"]])
self.assertEqual([action.payload["monsterId"] for action in self.planner.plan(self.snapshot, policy)],
[self.manual_target["id"]])
[self.representative["id"]])
self.representative["feel"] = self.catalog.max_feel(self.representative)
self.assertEqual(self.planner.plan(self.snapshot, policy), [])
if __name__ == "__main__":
+9 -1
View File
@@ -63,19 +63,27 @@ class GiftTimingTests(unittest.TestCase):
def test_success_response_updates_each_monster_despite_stale_queries(self):
with patch("ranch_assistant.model.time.time", return_value=NOW):
client = GiftClient(self.catalog)
client.raw["monsters"][1].update(typeId=1002010,
**{"g" + stat.capitalize(): self.catalog.monster(1002010)[stat + "_grow_min"]
for stat in ("atk", "def", "hp", "dex")})
engine = Engine(self.catalog, client)
engine.policy = gift_policy()
engine.auto = True
first, _, _ = engine.poll()
self.assertEqual(first.monsters[1]["feel"], 10)
self.assertEqual(first.monsters[1]["giftTime"], NOW)
engine.poll()
second, _, _ = engine.poll()
self.assertEqual(second.monsters[2]["feel"], 10)
self.assertEqual(second.monsters[2]["giftTime"], NOW)
engine.poll()
self.assertEqual([payload["monsterId"] for _, payload in client.calls], [1, 2])
def test_next_due_uses_earliest_eligible_cooldown_and_ignores_full_targets(self):
with patch("ranch_assistant.model.time.time", return_value=NOW):
snapshot = gift_snapshot(self.catalog)
snapshot.monsters[2].update(typeId=1002010,
**{"g" + stat.capitalize(): self.catalog.monster(1002010)[stat + "_grow_min"]
for stat in ("atk", "def", "hp", "dex")})
snapshot.monsters[1]["giftTime"] = (NOW - 7200 + 120) * 1000
snapshot.monsters[2]["giftTime"] = (NOW - 7200 + 15) * 1000
planner = GiftPlanner(self.catalog)
+5 -1
View File
@@ -56,7 +56,7 @@ class GrowthClient:
def call(self, path, payload):
self.calls.append((path, payload))
if path == "monsterService/monsterSell":
self.raw["monsters"] = []
self.raw["monsters"] = [mon for mon in self.raw["monsters"] if mon["id"] not in payload["monsterIds"]]
self.raw["stacks"][0]["monsterId"] = -1
return {"resCode": 0}
@@ -69,6 +69,10 @@ class GrowthTests(unittest.TestCase):
self.addCleanup(self.clock.stop)
def engine(self, client):
row = self.catalog.monster(1001010)
client.raw["monsters"].append({"id": 900, "typeId": 1001010, "process": 3, "mode": 2,
"level": 20, "roomId": 1, "lock": 0,
**{"g" + stat.capitalize(): row[stat + "_grow_min"] for stat in ("atk", "def", "hp", "dex")}})
engine = Engine(self.catalog, client)
engine.policy = Policy(manual_eggs=True, fill=False, buy=False, collect=False, protect_star=4, protect_quality=3,
egg_rules={"1001010": asdict(EggRule(enabled=True, action="sell", keep_count=0))})
@@ -60,6 +60,7 @@ 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 | {"id": 900, "process": 3, "level": 20, "roomId": 1})
client.value["monsters"].append(client.template)
client.value["stacks"][0]["monsterId"] = client.template["id"]
engine = Engine(catalog, client)
@@ -0,0 +1,319 @@
"""Offline regressions for stable cultivation primaries and gift target consent."""
from copy import deepcopy
import json
from pathlib import Path
from tempfile import TemporaryDirectory
import unittest
from unittest.mock import patch
from ranch_assistant.cultivation import CultivationSelector, growth_score, quality_rank
from ranch_assistant.gifts import GiftPlanner
from ranch_assistant.model import Catalog, Policy, Snapshot
NOW = 1_800_000_000
SPECIES = 1030010
MAIN = 949626937
STATS = ("atk", "def", "hp", "dex")
def monster(catalog, mid, grades="SASS", *, species=SPECIES, level=10, **values):
row = catalog.monster(species)
mon = {"id": mid, "typeId": species, "process": 3, "mode": 2, "level": level,
"feel": 0, "entangleLevel": 0, "giftTime": 0, "roomId": 1, "lock": 0}
for stat, grade in zip(STATS, grades):
low, high = row[stat + "_grow_min"], row[stat + "_grow_max"]
mon["g" + stat.capitalize()] = low + (high - low) * {"C": .125, "B": .375, "A": .625, "S": .875}[grade]
return mon | values
def snapshot(*members, owner=101):
return Snapshot({"master": {"id": owner}, "monsters": list(members), "teams": [], "stacks": [],
"items": [{"id": 91, "typeId": 30005, "num": 10}], "rooms": [{"id": 1}, {"id": 8}]})
def policy(*, auto=False, targets=None, **values):
return Policy(gift_enabled=True, gift_auto_representative=auto, keep_better_quality=False,
gift_targets=targets or {}, gift_liked_only=False,
gift_items={"30005": {"enabled": True, "reserve": 2}}, **values)
class PrimarySelectionTests(unittest.TestCase):
def setUp(self):
self.catalog = Catalog()
def test_highest_level_locked_main_wins_across_rooms_and_incubation(self):
main = monster(self.catalog, MAIN, level=20, lock=1, roomId=8)
rows = [monster(self.catalog, MAIN + 1, "SSSA", feel=99),
monster(self.catalog, MAIN + 2, "SSSS"), main,
monster(self.catalog, MAIN + 3, "SSSS", level=99, process=2)]
chosen = CultivationSelector(self.catalog).select(snapshot(*rows))
self.assertEqual(chosen, {str(SPECIES): main})
self.assertIs(chosen[str(SPECIES)], main)
def test_initial_selection_uses_level_then_feel_then_letter_grades(self):
low = monster(self.catalog, 1, "SSSS", level=9, feel=100)
no_feel = monster(self.catalog, 2, "SSSS")
high_average = monster(self.catalog, 3, "AAAA", feel=1)
more_s = monster(self.catalog, 4, "SCCC", feel=1)
self.assertGreater(growth_score(self.catalog, high_average), growth_score(self.catalog, more_s))
chosen = CultivationSelector(self.catalog).select(snapshot(low, no_feel, high_average, more_s))
self.assertEqual(chosen[str(SPECIES)]["id"], 4)
def normalized_catalog(self):
# Exact three-decimal values remove client rounding noise from equal-weight comparisons.
self.catalog.overrides[str(SPECIES)] = {
stat + suffix: value for stat, bounds in zip(STATS, ((1, 9), (10, 18), (100, 900), (2, 10)))
for suffix, value in zip(("_grow_min", "_grow_max"), bounds)}
def test_rank_weights_all_four_attributes_equally_without_positional_ties(self):
self.normalized_catalog()
selector = CultivationSelector(self.catalog)
ranks = [selector.rank(monster(self.catalog, index + 1, grades))
for index, grades in enumerate(("SCCC", "CSCC", "CCSC", "CCCS"))]
self.assertTrue(all(rank == ranks[0] for rank in ranks), ranks)
qualities = [quality_rank(self.catalog, monster(self.catalog, 1, grades))
for grades in ("SASS", "SSSA", "SSAS", "ASSS")]
self.assertTrue(all(rank == qualities[0] for rank in qualities), qualities)
def test_normalized_growth_gives_health_the_same_weight_as_other_stats(self):
self.normalized_catalog()
scores = []
for stat in STATS:
mon = monster(self.catalog, 1, "AAAA")
row = self.catalog.monster(SPECIES)
mon["g" + stat.capitalize()] = row[stat + "_grow_max"]
scores.append(growth_score(self.catalog, mon))
self.assertEqual(scores, [.71875] * 4)
def test_equal_s_counts_compare_all_attributes_instead_of_a_count_first(self):
self.normalized_catalog()
balanced = monster(self.catalog, 1, "SSBB")
weaker_average = monster(self.catalog, 2, "SSAC")
row = self.catalog.monster(SPECIES)
weaker_average["gDex"] = row["dex_grow_min"] + .1 * (row["dex_grow_max"] - row["dex_grow_min"])
self.assertEqual(self.catalog.quality(balanced).count(4), self.catalog.quality(weaker_average).count(4))
self.assertGreater(growth_score(self.catalog, balanced), growth_score(self.catalog, weaker_average))
self.assertGreater(quality_rank(self.catalog, balanced), quality_rank(self.catalog, weaker_average))
self.assertGreater(CultivationSelector(self.catalog).rank(balanced), CultivationSelector(self.catalog).rank(weaker_average))
def test_initial_exact_ties_always_choose_the_oldest_id(self):
rows = [monster(self.catalog, mid) for mid in (9, 2, 7)]
with patch("random.choice", side_effect=lambda members: max(members, key=lambda mon: mon["id"])):
for ordered in (rows, list(reversed(rows)), rows[1:] + rows[:1]):
self.assertEqual(CultivationSelector(self.catalog).select(snapshot(*ordered))[str(SPECIES)]["id"], 2)
def test_persisted_same_level_primary_cannot_be_stolen_by_better_newborn(self):
main = monster(self.catalog, MAIN, "CCCC", level=1)
data = snapshot(main)
with TemporaryDirectory() as folder:
path = Path(folder) / "cultivation_choices.json"
selector = CultivationSelector(self.catalog, path)
selector.select(data)
newborn = monster(self.catalog, MAIN + 1, "SSSS", level=1)
data.raw["monsters"] = [newborn, main]
self.assertGreater(selector.rank(newborn), selector.rank(main))
self.assertEqual(selector.select(data)[str(SPECIES)]["id"], MAIN)
self.assertEqual(CultivationSelector(self.catalog, path).select(data)[str(SPECIES)]["id"], MAIN)
self.assertEqual(json.loads(path.read_text(encoding="utf-8"))["choices"], {str(SPECIES): MAIN})
def test_same_level_feel_change_does_not_replace_an_established_primary(self):
main = monster(self.catalog, 9, "CCCC")
data = snapshot(main)
selector = CultivationSelector(self.catalog)
selector.select(data)
data.raw["monsters"] = [monster(self.catalog, 2, "SSSS", feel=99), main]
self.assertEqual(selector.select(data)[str(SPECIES)]["id"], 9)
def test_a_strictly_higher_level_mature_monster_can_take_over(self):
main = monster(self.catalog, 1, "SSSS", feel=99)
other = monster(self.catalog, 2, "CCCC", level=9)
data = snapshot(main, other)
selector = CultivationSelector(self.catalog)
self.assertEqual(selector.select(data)[str(SPECIES)]["id"], 1)
other["level"] = 11
self.assertEqual(selector.select(data)[str(SPECIES)]["id"], 2)
main["level"] = 11
self.assertEqual(selector.select(data)[str(SPECIES)]["id"], 2)
def test_cache_rebinds_to_current_cooldown_cap_and_task_flags(self):
main = monster(self.catalog, 1)
data = snapshot(main)
selector = CultivationSelector(self.catalog)
selector.select(data)
fresh = Snapshot(deepcopy(data.raw))
fresh.monsters[1].update(giftTime=NOW, entangleLevel=2, inExploreTeam=1)
selected = selector.select(fresh)[str(SPECIES)]
self.assertIs(selected, fresh.monsters[1])
self.assertEqual((selected["giftTime"], selected["entangleLevel"], selected["inExploreTeam"]), (NOW, 2, 1))
def test_present_non_ranch_primary_never_promotes_a_backup(self):
main = monster(self.catalog, 1, level=20)
backup = monster(self.catalog, 2, "SSSS")
data = snapshot(main, backup)
with TemporaryDirectory() as folder:
path = Path(folder) / "choices.json"
selector = CultivationSelector(self.catalog, path)
selector.select(data)
for process in (4, 2):
data.raw["monsters"] = [main | {"process": process}, backup]
self.assertEqual(selector.select(data), {})
self.assertEqual(CultivationSelector(self.catalog, path).select(data), {})
data.raw["monsters"] = [backup, main]
self.assertEqual(CultivationSelector(self.catalog, path).select(data)[str(SPECIES)]["id"], 1)
def test_confirmed_removal_promotes_one_replacement_and_persists_it(self):
main = monster(self.catalog, 1, level=20)
backup = monster(self.catalog, 2, "AAAA")
data = snapshot(main, backup)
with TemporaryDirectory() as folder:
path = Path(folder) / "choices.json"
selector = CultivationSelector(self.catalog, path)
selector.select(data)
data.raw["monsters"] = [main | {"process": 4}, backup]
self.assertEqual(selector.select(data), {})
data.raw["monsters"] = [backup]
self.assertEqual(selector.select(data)[str(SPECIES)]["id"], 2)
data.raw["monsters"].insert(0, monster(self.catalog, 3, "SSSS"))
self.assertEqual(selector.select(data)[str(SPECIES)]["id"], 2)
self.assertEqual(CultivationSelector(self.catalog, path).select(data)[str(SPECIES)]["id"], 2)
def test_empty_full_roster_clears_removed_choices_and_allows_a_new_first(self):
data = snapshot(monster(self.catalog, 1))
selector = CultivationSelector(self.catalog)
selector.select(data)
data.raw["monsters"] = []
self.assertEqual(selector.select(data), {})
self.assertEqual(selector.choices, {})
data.raw["monsters"] = [monster(self.catalog, 2)]
self.assertEqual(selector.select(data)[str(SPECIES)]["id"], 2)
def test_account_paths_and_owner_checks_isolate_prior_choices(self):
with TemporaryDirectory() as folder:
paths = [Path(folder) / account / "roles" / "101" / "choices.json" for account in ("a", "b")]
first, second = monster(self.catalog, 1), monster(self.catalog, 2)
for path, main in zip(paths, (first, second)):
CultivationSelector(self.catalog, path).select(snapshot(main))
for path, expected in zip(paths, (1, 2)):
self.assertEqual(CultivationSelector(self.catalog, path).select(snapshot(second, first))[str(SPECIES)]["id"], expected)
self.assertEqual(CultivationSelector(self.catalog, paths[1]).select(snapshot(second, first, owner=202))[str(SPECIES)]["id"], 1)
def test_unknown_quality_and_incubating_rows_are_not_mutated_or_promoted(self):
main = monster(self.catalog, 1, level=20, gHp=None)
young = monster(self.catalog, 3, "SSSS", level=99, process=2, mode=0)
data = snapshot(monster(self.catalog, 2, "SSSS"), young, main)
before = deepcopy(data.raw)
self.assertIsNone(quality_rank(self.catalog, main))
self.assertIsNone(quality_rank(self.catalog, young))
self.assertEqual(CultivationSelector(self.catalog).select(data)[str(SPECIES)]["id"], 1)
self.assertEqual(CultivationSelector(self.catalog).select(snapshot(young)), {})
self.assertEqual(data.raw, before)
def test_species_variants_with_the_same_name_remain_separate_types(self):
variants = [monster(self.catalog, index + 1, species=species)
for index, species in enumerate((1030010, 1030012, 1030013, 1030014))]
chosen = CultivationSelector(self.catalog).select(snapshot(*variants))
self.assertEqual(set(chosen), {"1030010", "1030012", "1030013", "1030014"})
class PrimaryGiftTests(unittest.TestCase):
def setUp(self):
self.catalog = Catalog()
self.enterContext(patch("ranch_assistant.model.time.time", return_value=NOW))
self.main = monster(self.catalog, MAIN, level=20, lock=1, roomId=8)
self.backup = monster(self.catalog, MAIN + 1, "SSSS")
self.equal_copy = monster(self.catalog, MAIN + 2, "SSSA")
self.other = monster(self.catalog, 30, "AAAA", species=1002010, level=15)
self.data = snapshot(self.backup, self.equal_copy, self.main, self.other)
self.planner = GiftPlanner(self.catalog)
def action_ids(self, selected_policy):
return [action.payload["monsterId"] for action in self.planner.plan(self.data, selected_policy)]
def test_only_checked_backups_never_authorize_the_unchecked_primary(self):
selected_policy = policy(targets={str(self.backup["id"]): 1, str(self.equal_copy["id"]): 2})
before = deepcopy(self.data.raw)
self.assertEqual(self.planner.candidates(self.data, selected_policy), [])
self.assertEqual(self.action_ids(selected_policy), [])
self.assertEqual(self.data.raw, before)
def test_manual_mode_intersects_primaries_and_keeps_multi_species_priorities(self):
selected_policy = policy(targets={str(self.backup["id"]): 1, str(self.other["id"]): 2,
str(self.main["id"]): 3, str(self.equal_copy["id"]): 4})
self.assertEqual([mon["id"] for mon in self.planner.candidates(self.data, selected_policy)], [30, MAIN])
self.assertEqual(self.action_ids(selected_policy), [30, MAIN])
def test_auto_mode_selects_all_species_primaries_under_old_quality_flag(self):
selected_policy = policy(auto=True, targets={str(self.backup["id"]): 1})
self.assertFalse(selected_policy.keep_better_quality)
self.assertEqual(self.action_ids(selected_policy), [MAIN, 30])
def test_full_cooling_or_busy_main_never_falls_back_in_either_mode(self):
for auto in (False, True):
for flags in ({"feel": self.catalog.max_feel(self.main)}, {"giftTime": NOW * 1000},
{"inExploreTeam": 1}, {"inBuild": 1}):
with self.subTest(auto=auto, flags=flags):
main = self.main | flags
self.data.raw["monsters"] = [self.backup, self.equal_copy, main, self.other]
selected_policy = policy(auto=auto, targets={str(MAIN): 1, str(self.backup["id"]): 2, "30": 3})
self.assertEqual(self.action_ids(selected_policy), [30])
self.assertEqual(self.planner.cultivation.select(self.data)[str(SPECIES)]["id"], MAIN)
def test_active_exploration_team_without_an_individual_flag_has_no_backup_fallback(self):
self.data.raw["exploreTeams"] = [{"id": 7, "status": 1, "monsters": str(MAIN)}]
for auto in (False, True):
with self.subTest(auto=auto):
selected_policy = policy(auto=auto, targets={str(MAIN): 1, str(self.backup["id"]): 2, "30": 3})
self.assertEqual(self.action_ids(selected_policy), [30])
def test_non_ranch_primary_stays_unselected_after_it_was_chosen(self):
selected_policy = policy(auto=True)
self.assertEqual(self.action_ids(selected_policy), [MAIN, 30])
for process in (4, 2):
self.data.raw["monsters"] = [self.backup, self.main | {"process": process}, self.other]
self.assertEqual(self.action_ids(selected_policy), [30])
def test_removed_primary_does_not_authorize_an_unchecked_replacement_in_manual_mode(self):
selected_policy = policy(targets={str(MAIN): 1})
self.assertEqual(self.action_ids(selected_policy), [MAIN])
self.data.raw["monsters"] = [self.backup, self.other]
self.assertEqual(self.action_ids(selected_policy), [])
self.assertEqual(self.planner.cultivation.select(self.data)[str(SPECIES)]["id"], self.backup["id"])
def test_earliest_due_only_uses_eligible_primaries_and_ignores_backups(self):
self.main["giftTime"] = (NOW - 7200 + 120) * 1000
self.backup["giftTime"] = (NOW - 7200 + 15) * 1000
self.other["giftTime"] = (NOW - 7200 + 60) * 1000
selected_policy = policy(targets={str(MAIN): 1, str(self.backup["id"]): 2, "30": 3})
self.assertEqual(self.action_ids(selected_policy), [])
self.assertEqual(self.planner.next_ready_at, NOW + 60)
self.other["feel"] = self.catalog.max_feel(self.other)
self.assertEqual(self.action_ids(selected_policy), [])
self.assertEqual(self.planner.next_ready_at, NOW + 120)
self.main["feel"] = self.catalog.max_feel(self.main)
self.assertEqual(self.action_ids(selected_policy), [])
self.assertIsNone(self.planner.next_ready_at)
def test_stock_reserves_and_item_locks_still_block_all_species(self):
selected_policy = policy(auto=True)
self.data.raw["items"][0]["num"] = 2
self.assertEqual(self.action_ids(selected_policy), [])
self.data.raw["items"][0]["num"] = 10
self.data.raw["items"][0]["feedLock"] = 1
self.assertEqual(self.action_ids(selected_policy), [])
self.data.raw["items"][0]["feedLock"] = 0
self.assertEqual(self.action_ids(selected_policy), [MAIN, 30])
self.assertTrue(all(action.payload["itemId"] == 91 for action in self.planner.plan(self.data, selected_policy)))
def test_current_confirmed_cooldown_prevents_gifts_to_same_species_copies(self):
selected_policy = policy(targets={str(MAIN): 1, str(self.backup["id"]): 2})
action = self.planner.plan(self.data, selected_policy)[0]
self.planner.remember_success(self.data, action, {"feel": 10, "giftDate": NOW * 1000})
stale = Snapshot(deepcopy(self.data.raw))
self.planner.apply_confirmed(stale)
self.assertEqual(self.planner.plan(stale, selected_policy), [])
self.assertEqual(stale.monsters[self.backup["id"]]["giftTime"], 0)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,437 @@
"""Offline integration: only the current primary may receive automatic resources."""
from copy import deepcopy
from dataclasses import asdict, replace
import json
from pathlib import Path
from tempfile import TemporaryDirectory
import time
import unittest
from unittest.mock import patch
from ranch_assistant.breakthrough import PATH, POTENTIAL_PATH
from ranch_assistant.engine import Engine
from ranch_assistant.model import Action, Catalog, Policy, Snapshot
from ranch_web.policies import default_config, export_config
from ranch_web.views import build_view, schema
SPECIES = 1001010
MAIN, BACKUP, EXTRA = 900, 901, 902
FEED = "monsterService/monsterIntensify"
GIFT = "monsterService/monsterSendGift"
RECIPIENT_KEYS = {"feed": "targetId", "gift": "monsterId", "potential": "monId", "breakthrough": "monId"}
def monster(catalog, mid, *, level=1, quality=0, **values):
species = values.get("typeId", SPECIES)
info = catalog.monster(species)
mon = {"id": mid, "typeId": species, "process": 3, "mode": 2, "level": level,
"potentialLevel": 1, "pAtk": 3, "pDef": 8, "pHp": 105, "pDex": 1,
"feel": 0, "giftTime": 0, "exp": 0, "tpLevel": 0, "tpExp": 0, "roomId": 1, "lock": 0}
for stat in ("atk", "def", "hp", "dex"):
low, high = info[stat + "_grow_min"], info[stat + "_grow_max"]
mon["g" + stat.capitalize()] = low + quality * (high - low)
return mon | values
class OfflineClient:
"""In-memory server with a recorded write/read boundary; never opens a socket."""
def __init__(self, catalog, *, complete=False):
self.raw = {"master": {"id": 1, "level": 30, "ti": 100, "money": 0, "ke": 0},
"monsters": [monster(catalog, MAIN, level=9, lock=1, pAtk=4 if complete else 3),
monster(catalog, BACKUP, quality=1), monster(catalog, EXTRA, level=2)],
"items": [{"id": 600, "typeId": 30058, "num": 100}, {"id": 601, "typeId": 30005, "num": 10}],
"rooms": [{"id": 1, "typeId": 1000}], "teams": [], "stacks": [],
"currentTasks": [], "history": {}, "activityHistory": {}, "exploreTeams": []}
self.calls, self.events = [], []
self.apply_writes = True
def snapshot(self):
self.events.append("snapshot")
return Snapshot(deepcopy(self.raw))
def call(self, path, payload):
self.calls.append((path, deepcopy(payload)))
self.events.append(path)
if not self.apply_writes:
return {"resCode": 0}
monsters = {int(mon["id"]): mon for mon in self.raw["monsters"]}
if path == POTENTIAL_PATH:
mon = monsters[payload["monId"]]
mon["p" + payload["monsterAttr"].capitalize()] += 1
elif path == PATH:
monsters[payload["monId"]]["potentialLevel"] += 1
elif path == GIFT:
mon = monsters[payload["monsterId"]]
mon.update(feel=mon["feel"] + 10, giftTime=int(time.time()) * 1000)
return {"feel": mon["feel"], "giftDate": mon["giftTime"], "resCode": 0}
elif path in (FEED, "monsterService/monsterSell"):
consumed = set(payload["foods"] if path == FEED else payload["monsterIds"])
self.raw["monsters"] = [mon for mon in self.raw["monsters"] if mon["id"] not in consumed]
else:
raise AssertionError("Unexpected offline write: " + path)
return {"resCode": 0}
class PrimaryResourceAdmissionTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.catalog = Catalog()
def engine(self, *, complete=False):
temporary = TemporaryDirectory(prefix="primary-admission-")
self.addCleanup(temporary.cleanup)
client = OfflineClient(self.catalog, complete=complete)
engine = Engine(self.catalog, client, Path(temporary.name) / "budget.json")
engine.master_sync.settle = lambda *args: None
engine.settle_pending_growth = lambda *args, **kwargs: False
engine.policy = Policy(fill=False, collect=False, dispatch=False, feed=False,
manual_eggs=True, protect_star=6, protect_quality=5, keep_better_quality=False,
gift_auto_representative=False,
egg_rules={str(SPECIES): {"enabled": True, "action": "feed", "keep_count": 0}})
engine.snapshot = client.snapshot()
engine.auto = True
return engine, client
def action(self, kind, recipient):
payload = {RECIPIENT_KEYS[kind]: recipient}
if kind == "feed":
payload["foods"] = [EXTRA]
elif kind == "gift":
payload["itemId"] = 601
elif kind == "potential":
payload.update(itemId=600, monsterAttr="atk", traceInfo={"itemTypeId": 600, "itemNum": 100})
else:
payload["itemIds"] = [600]
return Action(kind, "offline " + kind, {"feed": FEED, "gift": GIFT, "potential": POTENTIAL_PATH, "breakthrough": PATH}[kind], payload)
def config(self, engine):
config = default_config()
config["policy"] = asdict(engine.policy)
return config
def test_stale_breakthrough_targets_never_spend_or_enable_the_unchecked_primary(self):
for complete in (False, True):
for fast in (False, True):
with self.subTest(complete=complete, fast=fast):
engine, client = self.engine(complete=complete)
engine.policy.breakthrough_targets = {str(BACKUP): 1}
before = asdict(engine.policy)
_, plans, message = engine.poll_automation("breakthrough") if fast else engine.poll()
self.assertEqual(client.calls, [])
self.assertFalse(any(action.kind in ("potential", "breakthrough") for action in plans))
self.assertIn("非主培养", message)
self.assertIn("#900", message)
self.assertEqual(asdict(engine.policy), before)
self.assertIsNone(engine._breakthrough_pending)
self.assertFalse(engine.last_executed)
def test_stale_priority_cannot_bypass_primary_admission_on_either_scheduler(self):
for complete in (False, True):
for fast in (False, True):
with self.subTest(complete=complete, fast=fast):
engine, client = self.engine(complete=complete)
engine.policy.breakthrough_targets = {str(BACKUP): 1, str(MAIN): 2}
before = asdict(engine.policy)
engine.poll_automation("breakthrough") if fast else engine.poll()
self.assertEqual(client.calls, [(PATH if complete else POTENTIAL_PATH,
{"monId": MAIN, "itemIds": [600]} if complete else
{"monId": MAIN, "itemId": 600, "monsterAttr": "atk", "traceInfo": {"itemTypeId": 600, "itemNum": 100}})])
self.assertEqual(client.events[-1], "snapshot")
self.assertIsNone(engine._breakthrough_pending)
self.assertEqual(asdict(engine.policy), before)
def test_engine_filters_stale_actions_even_if_a_source_planner_returns_them(self):
for kind in RECIPIENT_KEYS:
with self.subTest(kind=kind):
engine, client = self.engine()
source = engine.planner if kind == "feed" else engine.gift_planner if kind == "gift" else engine.breakthrough_planner
stale = self.action(kind, BACKUP)
if kind in ("potential", "breakthrough"):
engine.policy.breakthrough_targets = {str(BACKUP): 1}
with patch.object(source, "plan", return_value=stale if kind in ("potential", "breakthrough") else [stale]):
_, plans, message = engine.poll()
self.assertFalse(any(action.kind == kind for action in plans))
self.assertEqual(client.calls, [])
self.assertIn("非主培养", message)
def test_current_recipient_is_checked_after_planning_on_both_dispatch_paths(self):
for kind in RECIPIENT_KEYS:
for fast in (False, True):
if fast and kind == "feed":
continue
with self.subTest(kind=kind, fast=fast):
engine, client = self.engine()
engine.cultivation.select(engine.snapshot)
action = self.action(kind, MAIN)
def stale_plan():
# A newer roster makes the queued recipient a duplicate.
engine.snapshot.monsters[BACKUP]["level"] = 30
return [action]
with patch.object(engine, "plans", side_effect=stale_plan):
_, _, message = engine.poll_automation("gift" if kind == "gift" else "breakthrough") if fast else engine.poll()
self.assertEqual(client.calls, [])
self.assertIn("非主培养", message)
self.assertFalse(engine.last_executed)
self.assertIsNone(engine._breakthrough_pending)
self.assertEqual(engine.gift_planner.confirmed, {})
def test_busy_primary_blocks_real_resource_plans_without_falling_back(self):
for busy in ("team_list", "team_string", "inExploreTeam", "inBuild", "sysLock"):
for complete in (False, True):
for scheduler in ("poll", "gift", "breakthrough"):
with self.subTest(busy=busy, complete=complete, scheduler=scheduler):
engine, client = self.engine(complete=complete)
client.raw["monsters"][0] = monster(self.catalog, MAIN, level=9, quality=.5,
lock=1, pAtk=4 if complete else 3)
client.raw["monsters"][2] = monster(self.catalog, EXTRA, level=2, quality=.125)
if busy.startswith("team_"):
# Authoritative team membership can arrive without the per-monster marker.
client.raw["exploreTeams"] = [{"id": 77, "status": 1,
"monsters": [MAIN] if busy == "team_list" else str(MAIN)}]
else:
client.raw["monsters"][0][busy] = 1
targets = {str(MAIN): 1, str(BACKUP): 2}
engine.policy = replace(engine.policy, feed=True, feed_targets=targets,
gift_enabled=True, gift_targets=targets, gift_liked_only=False,
gift_items={"30005": {"enabled": True, "reserve": 0}}, breakthrough_targets=targets)
engine.planner.managed.add(EXTRA)
before = asdict(engine.policy)
_, plans, _ = engine.poll() if scheduler == "poll" else engine.poll_automation(scheduler)
self.assertEqual(client.calls, [])
self.assertFalse(any(action.kind in RECIPIENT_KEYS for action in plans))
self.assertEqual(engine.cultivation.select(engine.snapshot)[str(SPECIES)]["id"], MAIN)
self.assertEqual(asdict(engine.policy), before)
self.assertIsNone(engine._breakthrough_pending)
def test_exploration_becoming_active_after_planning_blocks_queued_resources(self):
for kind in RECIPIENT_KEYS:
for fast in (False, True):
if fast and kind == "feed":
continue
with self.subTest(kind=kind, fast=fast):
engine, client = self.engine()
action = self.action(kind, MAIN)
def busy_plan():
engine.snapshot.raw["exploreTeams"] = [{"id": 77, "status": 1, "monsters": str(MAIN)}]
return [action]
with patch.object(engine, "plans", side_effect=busy_plan):
_, _, message = engine.poll_automation("gift" if kind == "gift" else "breakthrough") if fast else engine.poll()
self.assertEqual(client.calls, [])
self.assertIn("正在探险", message)
self.assertFalse(engine.last_executed)
self.assertIsNone(engine._breakthrough_pending)
def test_material_recipient_is_rechecked_after_unsent_intent_is_persisted(self):
engine, client = self.engine()
action = self.action("potential", MAIN)
save = engine._save_automation_state
def newer_roster_after_save():
save()
engine.snapshot.monsters[BACKUP]["level"] = 30
with patch.object(engine, "_save_automation_state", side_effect=newer_roster_after_save):
_, _, message = engine._execute_breakthrough(action)
self.assertEqual(client.calls, [])
self.assertIn("非主培养", message)
self.assertIsNone(engine._breakthrough_pending)
self.assertIsNone(json.loads(engine.automation_state_path.read_text(encoding="utf-8"))["breakthrough"])
self.assertFalse(engine.last_executed)
def test_existing_pending_evidence_survives_loss_of_primary_and_restart(self):
for complete in (False, True):
with self.subTest(complete=complete):
engine, client = self.engine(complete=complete)
client.apply_writes = False
engine.policy.breakthrough_targets = {str(MAIN): 1}
engine.poll_automation("breakthrough")
pending = deepcopy(engine._breakthrough_pending)
self.assertIsNotNone(pending)
client.raw["monsters"][1]["level"] = 30
engine.poll_automation("breakthrough")
self.assertEqual(engine._breakthrough_pending, pending)
self.assertEqual(len(client.calls), 1)
self.assertEqual(json.loads(engine.automation_state_path.read_text(encoding="utf-8"))["breakthrough"], pending)
restored = Engine(self.catalog, client, engine.automation_state_path.parent / "budget.json")
restored.master_sync.settle = lambda *args: None
restored.policy, restored.auto = engine.policy, True
restored.poll_automation("breakthrough")
self.assertEqual(restored._breakthrough_pending["payload"], pending["payload"])
self.assertEqual(len(client.calls), 1)
# Confirmation belongs to the original recipient, even now a backup.
original = client.raw["monsters"][0]
original["potentialLevel" if complete else "pAtk"] += 1
restored.poll_automation("breakthrough")
self.assertIsNone(restored._breakthrough_pending)
self.assertEqual(len(client.calls), 1)
def test_preexisting_pending_record_is_not_discarded_when_rejecting_a_new_target(self):
engine, client = self.engine()
pending = {"kind": "invalid", "role_id": "1", "uncertain": True, "message": "retain evidence"}
engine._breakthrough_pending = deepcopy(pending)
engine._save_automation_state()
persisted = engine.automation_state_path.read_bytes()
engine._execute_breakthrough(self.action("potential", BACKUP))
self.assertEqual(engine._breakthrough_pending, pending)
self.assertEqual(engine.automation_state_path.read_bytes(), persisted)
self.assertEqual(client.calls, [])
def test_actual_gift_dispatch_uses_only_checked_primary_without_enabling_it(self):
for fast in (False, True):
for include_primary in (False, True):
with self.subTest(fast=fast, include_primary=include_primary):
engine, client = self.engine()
targets = {str(BACKUP): 1} | ({str(MAIN): 2} if include_primary else {})
engine.policy = replace(engine.policy, gift_enabled=True, gift_targets=targets,
gift_liked_only=False, gift_items={"30005": {"enabled": True, "reserve": 0}})
before = asdict(engine.policy)
_, _, message = engine.poll_automation("gift") if fast else engine.poll()
self.assertEqual([payload["monsterId"] for path, payload in client.calls if path == GIFT],
[MAIN] if include_primary else [])
if not include_primary:
self.assertIn("非主培养", message)
self.assertEqual(asdict(engine.policy), before)
def test_actual_feeding_dispatches_only_the_primary_with_legacy_flags_off(self):
for explicit in (False, True):
with self.subTest(explicit=explicit):
engine, client = self.engine()
# Equal-quality extras are dispatched; this case exercises feeding inferior material.
client.raw["monsters"][0] = monster(self.catalog, MAIN, level=9, quality=.5, lock=1)
client.raw["monsters"][2] = monster(self.catalog, EXTRA, level=2, quality=.125)
engine.policy = replace(engine.policy, feed=True, gift_auto_representative=True,
feed_targets={str(BACKUP): 1, str(MAIN): 2} if explicit else {})
engine.planner.managed.add(EXTRA)
before = asdict(engine.policy)
engine.poll()
self.assertEqual(client.calls, [(FEED, {"targetId": MAIN, "foods": [EXTRA]})])
self.assertEqual(set(engine.snapshot.monsters), {MAIN, BACKUP})
self.assertEqual(client.events[-1], "snapshot")
self.assertEqual(asdict(engine.policy), before)
def test_full_primary_and_stale_explicit_selection_cannot_feed_a_backup(self):
for explicit in (False, True):
with self.subTest(explicit=explicit):
engine, client = self.engine()
engine.policy = replace(engine.policy, feed=True, gift_auto_representative=True,
feed_targets={str(BACKUP): 1} if explicit else {})
if not explicit:
main = client.raw["monsters"][0]
main.update(level=self.catalog.max_level(main), tpLevel=4,
tpExp=engine.planner.tp_thresholds(main)[4])
engine.planner.managed.add(EXTRA)
before = asdict(engine.policy)
engine.poll()
self.assertEqual(client.calls, [])
self.assertEqual(set(engine.snapshot.monsters), {MAIN, BACKUP, EXTRA})
self.assertEqual(asdict(engine.policy), before)
def test_manual_explicit_feed_can_still_target_a_backup(self):
engine, client = self.engine()
engine.manage_monsters("feed", [EXTRA], BACKUP)
self.assertEqual(client.calls, [(FEED, {"targetId": BACKUP, "foods": [EXTRA]})])
self.assertNotIn(EXTRA, engine.snapshot.monsters)
self.assertFalse(engine.auto)
def test_web_roles_disable_stale_selections_but_preserve_config_and_manual_targets(self):
engine, client = self.engine()
engine.policy = replace(engine.policy, feed_targets={str(BACKUP): 1},
gift_targets={str(BACKUP): 2}, breakthrough_targets={str(BACKUP): 3})
before = asdict(engine.policy)
config = self.config(engine)
config_before = deepcopy(config)
dto = build_view(engine, "ranch", config)
rows = {row["id"]: row for row in dto["rows"]}
self.assertEqual([rows[str(mid)]["cultivation_role_key"] for mid in (MAIN, BACKUP, EXTRA)],
["primary", "backup", "duplicate"])
for prefix in ("feed", "gift", "breakthrough"):
self.assertTrue(rows[str(BACKUP)][prefix + "_selected"])
self.assertFalse(rows[str(MAIN)][prefix + "_selected"])
for mid in (BACKUP, EXTRA):
edit = rows[str(mid)]["edits"][prefix + "_selected"]
self.assertTrue(edit["disabled"])
self.assertIn("#900", edit["reason"])
self.assertFalse(rows[str(MAIN)]["edits"][prefix + "_selected"]["disabled"])
self.assertIn(BACKUP, [option["value"] for option in dto["feed_targets"]])
self.assertEqual(asdict(engine.policy), before)
self.assertEqual(config, config_before)
self.assertEqual(client.calls, [])
def test_web_retention_is_fixed_and_legacy_values_round_trip_without_a_toggle(self):
for stored in (0, 1, 8):
with self.subTest(stored=stored):
engine, client = self.engine()
engine.policy.egg_rules[str(SPECIES)]["keep_count"] = stored
config = self.config(engine)
before = deepcopy(config)
dto = build_view(engine, "bag", config, {"category": "eggs"})
row = next(row for row in dto["rows"] if row["id"] == str(SPECIES))
column = next(column for column in dto["columns"] if column["key"] == "retention_text")
self.assertEqual(row["retention_text"], "主培养1 + 更优备选≤1")
self.assertFalse(column.get("edit"))
self.assertFalse(any(column["key"] == "keep_count" and column.get("edit") for column in dto["columns"]))
fields = [field for page in schema(self.catalog)["pages"] for field in page["form"]]
self.assertFalse(any(field["path"] == ["policy", "keep_better_quality"] for field in fields))
self.assertEqual(export_config(config, engine.snapshot)["policy"]["egg_rules"][str(SPECIES)]["keep_count"], stored)
self.assertEqual(config, before)
self.assertEqual(client.calls, [])
def test_busy_primary_keeps_its_web_role_while_automatic_controls_are_disabled(self):
engine, client = self.engine()
client.raw["exploreTeams"] = [{"id": 77, "status": 1, "monsters": str(MAIN)}]
engine.snapshot = client.snapshot()
engine.policy = replace(engine.policy, feed_targets={str(MAIN): 1},
gift_targets={str(MAIN): 1}, breakthrough_targets={str(MAIN): 1})
rows = {int(row["id"]): row for row in build_view(engine, "ranch", self.config(engine))["rows"]}
self.assertEqual(rows[MAIN]["cultivation_role_key"], "primary")
self.assertEqual(rows[MAIN]["cultivation_role"], "主培养")
self.assertEqual(rows[MAIN]["primary_id"], MAIN)
self.assertFalse(rows[MAIN]["automatic_eligible"])
self.assertIn("正在探险", rows[MAIN]["automatic_reason"])
self.assertEqual(rows[BACKUP]["cultivation_role_key"], "backup")
for prefix in ("feed", "gift", "breakthrough"):
self.assertTrue(rows[MAIN][prefix + "_selected"])
self.assertTrue(rows[MAIN]["edits"][prefix + "_selected"]["disabled"])
self.assertEqual(client.calls, [])
def test_web_existing_extras_report_protection_and_dispatch_off_without_managed_history(self):
engine, client = self.engine()
client.raw["monsters"] += [monster(self.catalog, 903, lock=1), monster(self.catalog, 904, equip1=123),
monster(self.catalog, 905, typeId=1030010)]
engine.snapshot = client.snapshot()
self.assertEqual(engine.planner.managed, set())
rows = {int(row["id"]): row for row in build_view(engine, "ranch", self.config(engine))["rows"]}
self.assertIn("自动派遣", rows[EXTRA]["scope"])
self.assertIn("关闭", rows[EXTRA]["scope"])
self.assertNotIn("已有:不自动处理", rows[EXTRA]["scope"])
self.assertIn("已锁定", rows[903]["scope"])
self.assertIn("携带装备", rows[904]["scope"])
self.assertIn("规则未启用", rows[905]["scope"])
self.assertEqual(client.calls, [])
def test_web_uses_the_retention_planners_reserve_when_replacement_is_still_incubating(self):
engine, client = self.engine()
client.raw["monsters"][1] = monster(self.catalog, BACKUP, quality=.5)
client.raw["monsters"].append(monster(self.catalog, 903, quality=1, process=2))
engine.snapshot = client.snapshot()
rows = {int(row["id"]): row for row in build_view(engine, "ranch", self.config(engine))["rows"]}
self.assertEqual(rows[BACKUP]["cultivation_role_key"], "duplicate")
self.assertEqual(rows[903]["cultivation_role_key"], "backup")
self.assertIn("待收取", rows[903]["cultivation_role"])
self.assertFalse(rows[903]["automatic_eligible"])
self.assertTrue(rows[903]["edits"]["feed_selected"]["disabled"])
self.assertEqual(client.calls, [])
def test_same_name_variants_have_independent_primary_admission_and_web_roles(self):
engine, client = self.engine()
for mid, species in enumerate((1030010, 1030012, 1030013, 1030014), 1000):
client.raw["monsters"].append(monster(self.catalog, mid, typeId=species, level=1))
engine.snapshot = client.snapshot()
rows = {int(row["id"]): row for row in build_view(engine, "ranch", self.config(engine))["rows"]}
for mid in range(1000, 1004):
self.assertEqual(rows[mid]["cultivation_role_key"], "primary")
self.assertTrue(rows[mid]["automatic_eligible"])
self.assertEqual(client.calls, [])
if __name__ == "__main__":
unittest.main()
@@ -1,6 +1,8 @@
import copy
import json
import time
import unittest
from unittest.mock import patch
from ranch_assistant.breakthrough import POTENTIAL_PATH
from ranch_assistant.engine import Engine
@@ -20,6 +22,17 @@ def raw(catalog):
return value
def species_monster(catalog, mid, grades, *, level=10, species=1030010, **values):
row = catalog.monster(species)
mon = {"id": mid, "typeId": species, "process": 3, "mode": 2, "level": level,
"exp": 0, "potentialLevel": 2, "tpLevel": 4, "tpExp": 9999,
"feel": 0, "giftTime": 0, "entangleLevel": 0, "lock": 0, "roomId": 1}
for stat, grade in zip(("atk", "def", "hp", "dex"), grades):
low, high = row[stat + "_grow_min"], row[stat + "_grow_max"]
mon["g" + stat.capitalize()] = low + (high - low) * {"C": .1, "B": .375, "A": .625, "S": .9}[grade]
return mon | values
class FakeClient:
def __init__(self, value):
self.value, self.calls = value, []
@@ -35,18 +48,170 @@ class FakeClient:
return copy.deepcopy(self.response)
class StatefulRanchClient(FakeClient):
def call(self, path, payload):
super().call(path, copy.deepcopy(payload))
monsters = {int(mon["id"]): mon for mon in self.value["monsters"]}
removed = []
if path == "monsterService/monsterSell":
removed = payload["monsterIds"]
elif path == "stackService/stackTransferMonster":
for data in payload["datas"]:
for mid in data["monsterId"]:
monsters[mid].update(process=3, roomId=data["roomId"])
for stack in self.value["stacks"]:
if stack.get("monsterId") == mid:
stack["monsterId"] = 0
elif path == "monsterService/monsterIntensify":
removed = payload["foods"]
elif path == "monsterService/monsterSendGift":
mon = monsters[payload["monsterId"]]
mon.update(feel=int(mon.get("feel") or 0) + 1, giftTime=int(time.time() * 1000))
return {"feel": mon["feel"], "giftDate": mon["giftTime"]}
elif path == POTENTIAL_PATH:
mon = monsters[payload["monId"]]
stat = "p" + payload["monsterAttr"].capitalize()
mon[stat] += 1
else:
raise AssertionError(f"Unexpected offline ranch operation: {path}")
self.value["monsters"] = [mon for mon in self.value["monsters"] if mon["id"] not in removed]
for stack in self.value["stacks"]:
if stack.get("monsterId") in removed:
stack["monsterId"] = 0
return {"resCode": 0}
class RanchAutomationIntegrationTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.catalog = Catalog()
def engine(self, folder, value=None):
client = FakeClient(value or raw(self.catalog))
def engine(self, folder, value=None, client_type=FakeClient):
client = client_type(value or raw(self.catalog))
engine = Engine(self.catalog, client, folder / "budget.json")
engine.master_sync.settle = lambda *args: None
engine.settle_pending_growth = lambda *args, **kwargs: False
return engine, client
def test_screenshot_lv20_sass_primary_never_spends_on_four_lesser_duplicates(self):
primary = species_monster(self.catalog, 900, "SASS", level=20,
pAtk=44, pDef=10, pHp=180, pDex=9)
primary["feel"] = self.catalog.max_feel(primary)
duplicates = [species_monster(self.catalog, 901 + index, grades, level=9 + index % 2,
tpLevel=0, tpExp=0, pAtk=1, pDef=1, pHp=1, pDex=1)
for index, grades in enumerate(("SAAA", "ASAS", "AASS", "AAAS"))]
duplicate_ids = {mon["id"] for mon in duplicates}
cases = [({}, False, {}), ({"900": 1, "901": 2, "902": 3, "903": 4, "904": 5}, False, {}),
({}, True, {}), ({}, False, {"901": 1})]
for feed_targets, manual_gifts, potential_targets in cases:
with self.subTest(feed_targets=feed_targets, manual_gifts=manual_gifts, potential_targets=potential_targets):
with workspace_temp() as folder:
value = raw(self.catalog)
value.update(monsters=copy.deepcopy([primary, *duplicates]),
items=[{"id": 600, "typeId": 30058, "num": 100},
{"id": 601, "typeId": 30005, "num": 10}])
engine, client = self.engine(folder, value, StatefulRanchClient)
engine.policy = Policy(enabled=True, dispatch=True, feed=True, manual_eggs=True,
fill=False, protect_star=4, protect_quality=5, keep_better_quality=False,
egg_rules={"1030010": {"enabled": True, "action": "feed", "keep_count": 1}},
feed_targets=feed_targets, breakthrough_targets=potential_targets,
gift_enabled=manual_gifts, gift_auto_representative=not manual_gifts,
gift_targets={str(mid): mid for mid in duplicate_ids | {900}},
gift_liked_only=False, gift_items={"30005": {"enabled": True}})
engine.planner.managed.update(duplicate_ids | {900})
engine.auto = True
_, plans, _ = engine.poll()
for path, payload in client.calls:
target = payload.get("targetId", payload.get("monsterId", payload.get("monId")))
self.assertNotIn(target, duplicate_ids, (path, payload))
self.assertNotIn(900, payload.get("foods", []) + payload.get("monsterIds", []))
for action in plans:
if action.kind in ("feed", "gift", "potential", "breakthrough"):
target = action.payload.get("targetId", action.payload.get("monsterId", action.payload.get("monId")))
self.assertNotIn(target, duplicate_ids, action)
self.assertIn(900, engine.snapshot.monsters)
def test_existing_enabled_duplicates_cleanup_without_managed_and_preserve_constraints(self):
for constraint in (None, "lock", "sysLock", "equip1", "team", "entangle", "inExploreTeam", "inBuild", "unknown_quality", "active_exploration_team", "active_exploration_team_csv", "stale_targets_high_rarity"):
with self.subTest(constraint=constraint):
with workspace_temp() as folder:
value = raw(self.catalog)
stale_targets = constraint == "stale_targets_high_rarity"
species = next(int(key) for key, row in self.catalog.monsters.items()
if row.get("star") == 5 and not row.get("npc")
and all(row.get(stat + "_grow_min") is not None for stat in ("atk", "def", "hp", "dex"))) if stale_targets else 1030010
rows = [species_monster(self.catalog, 900, "SASS", level=20, species=species)]
rows += [species_monster(self.catalog, mid, "CCCC", species=species) for mid in range(901, 905)]
rows += [species_monster(self.catalog, 950 + index, "CCCC", species=species)
for index, species in enumerate((1030012, 1030013, 1030014))]
value.update(monsters=rows, teams=[])
if constraint == "team":
value["teams"] = [{"monsters": [901]}]
elif constraint in ("active_exploration_team", "active_exploration_team_csv"):
value["exploreTeams"][0].update(status=1,
monsters="901" if constraint.endswith("_csv") else [901], endTime=9999999999999)
elif constraint == "unknown_quality":
rows[1]["gAtk"] = None
elif constraint and not stale_targets:
rows[1][constraint] = 1
engine, client = self.engine(folder, value, StatefulRanchClient)
engine.policy = Policy(manual_eggs=True, fill=False, protect_star=4, protect_quality=5,
keep_better_quality=False, gift_auto_representative=False,
egg_rules={str(species): {"enabled": True, "action": "sell", "keep_count": 0}},
feed_targets={str(mid): mid for mid in range(900, 905)} if stale_targets else {},
gift_targets={str(mid): mid for mid in range(900, 905)} if stale_targets else {},
breakthrough_targets={str(mid): mid for mid in range(900, 905)} if stale_targets else {})
self.assertEqual(engine.planner.managed, set())
engine.auto = True
for _ in range(5):
engine.poll()
expected = {900, 950, 951, 952} | ({901} if constraint and not stale_targets else set())
self.assertEqual(set(engine.snapshot.monsters), expected)
self.assertTrue(client.calls)
self.assertTrue(all(path == "monsterService/monsterSell" for path, _ in client.calls))
if constraint and not stale_targets:
self.assertTrue(engine.planner.statuses.get(901))
if constraint == "lock":
self.assertEqual(engine.snapshot.monsters[901]["lock"], 1)
if constraint in ("active_exploration_team", "active_exploration_team_csv"):
client.value["exploreTeams"][0]["status"] = 0
engine.poll()
self.assertEqual(set(engine.snapshot.monsters), {900, 950, 951, 952})
self.assertEqual(client.calls[-1], ("monsterService/monsterSell", {"monsterIds": [901]}))
def test_successive_quality_backups_replace_before_collect_and_new_mature_ties_dispatch(self):
with workspace_temp() as folder:
value = raw(self.catalog)
room_type = next(key for key, row in self.catalog.data["room_info"].items() if row.get("maxNum", 0) >= 2)
value.update(monsters=[species_monster(self.catalog, 900, "SASS", level=20, lock=1),
species_monster(self.catalog, 901, "SSSA"),
species_monster(self.catalog, 902, "SSSS", level=1, process=2, roomId=None)],
rooms=[{"id": 1, "typeId": int(room_type)}],
stacks=[{"id": 1, "position": 0, "monsterId": 902}])
row = self.catalog.monster(1030010)
for stat, scale in zip(("atk", "def", "hp", "dex"), (.95, .95, .95, .7)):
value["monsters"][1]["g" + stat.capitalize()] = row[stat + "_grow_min"] + scale * (row[stat + "_grow_max"] - row[stat + "_grow_min"])
engine, client = self.engine(folder, value, StatefulRanchClient)
engine.policy = Policy(manual_eggs=True, fill=False, protect_star=4, protect_quality=5,
keep_better_quality=False, gift_auto_representative=False,
egg_rules={"1030010": {"enabled": True, "action": "sell", "keep_count": 4}})
engine.auto = True
with patch.dict(self.catalog.data["room_info"][room_type], {"maxNum": 2}):
engine.poll()
self.assertEqual(client.calls, [("monsterService/monsterSell", {"monsterIds": [901]})])
engine.poll()
self.assertEqual(client.calls[-1], ("stackService/stackTransferMonster",
{"datas": [{"monsterId": [902], "roomId": 1}]}))
self.assertEqual(set(engine.snapshot.monsters), {900, 902})
client.value["monsters"].insert(0,
species_monster(self.catalog, 903, "SSSS", level=1, process=2, roomId=None))
client.value["stacks"][0]["monsterId"] = 903
engine.poll()
self.assertEqual(client.calls[-1], ("monsterService/monsterSell", {"monsterIds": [903]}))
self.assertEqual(set(engine.snapshot.monsters), {900, 902})
engine.poll()
self.assertEqual(len(client.calls), 3)
def test_breakthrough_targets_execute_and_require_new_snapshot_before_repeat(self):
with workspace_temp() as folder:
engine, client = self.engine(folder)
+63 -34
View File
@@ -27,47 +27,49 @@ class RanchRetentionTests(unittest.TestCase):
def policy(self, action="sell", count=1, **values):
values.setdefault("protect_star", 6)
return Policy(manual_eggs=True, fill=False, protect_quality=6, keep_better_quality=True,
values.setdefault("protect_quality", 5)
values.setdefault("keep_better_quality", False)
return Policy(manual_eggs=True, fill=False,
egg_rules={"1001010": asdict(EggRule(enabled=True, action=action, keep_count=count))}, **values)
def plan(self, rows, policy=None, managed=None):
self.snapshot.raw["monsters"] = rows
self.planner.managed.update(managed if managed is not None else [row["id"] for row in rows])
self.planner.cultivation.choices["1001010"] = 1
self.planner.cultivation.signature = None
return self.planner.plan(self.snapshot, policy or self.policy())
def test_quality_uses_s_then_a_then_b_before_normalized_growth(self):
def test_quality_uses_s_count_then_equal_weight_normalized_growth(self):
aasa, ssas = graded_monster(self.catalog, 1, "AASA", level=50), graded_monster(self.catalog, 2, "SSAS")
self.assertLess(quality_rank(self.catalog, aasa), quality_rank(self.catalog, ssas))
self.assertGreater(quality_rank(self.catalog, graded_monster(self.catalog, 3, "AAAC")),
self.assertLess(quality_rank(self.catalog, graded_monster(self.catalog, 3, "AAAC")),
quality_rank(self.catalog, graded_monster(self.catalog, 4, "BBAA")))
self.assertFalse(any(a.kind == "sell" for a in self.plan([aasa, ssas])))
reason = self.planner.protection_reason(ssas, self.snapshot, self.policy())
self.assertIn("SSAS", reason)
self.assertIn("S项3", reason)
def test_quota_zero_one_two_apply_to_every_enabled_action(self):
def test_legacy_quota_zero_one_two_always_reserves_one_primary(self):
for action in ("sell", "feed", "keep"):
for quota, disposed in ((0, 3), (1, 2), (2, 1)):
for quota in (0, 1, 2):
with self.subTest(action=action, quota=quota):
disposed = 2
rows = [graded_monster(self.catalog, mid, "CCCC", tpLevel=4) for mid in (1, 2, 3)]
if action == "feed":
target = graded_monster(self.catalog, 99, "SSSS", species=1002010,
level=1, exp=0, potentialLevel=2, tpLevel=4, tpExp=33)
rows.append(target)
elif action == "keep":
disposed = 0
policy = self.policy(action=action, count=quota,
feed_targets={"99": 1} if action == "feed" else {})
actions = self.plan(rows, policy)
self.assertIn(1, self.planner.retained)
self.assertNotIn(2, self.planner.retained)
self.assertNotIn(3, self.planner.retained)
sold = [mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]]
fed = [mid for a in actions if a.kind == "feed" for mid in a.payload["foods"] if mid != 99]
self.assertEqual(len(sold + fed), disposed)
for target in (a.payload["targetId"] for a in actions if a.kind == "feed"):
self.assertNotIn(target, fed)
def test_same_batch_and_locked_ranch_monsters_share_one_quota(self):
def test_locked_ranch_duplicates_stay_locked_and_equal_mature_extras_dispatch(self):
rows = [graded_monster(self.catalog, mid, "CCCC", roomId=mid) for mid in (1, 2)]
rows += [graded_monster(self.catalog, mid, "CCCC", process=2, roomId=None) for mid in (3, 4)]
for row in rows[:2]:
@@ -75,48 +77,67 @@ class RanchRetentionTests(unittest.TestCase):
actions = self.plan(rows, self.policy(count=2))
self.assertEqual([mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]], [3, 4])
def test_incubator_batch_fills_quota_and_keeps_same_ids_after_collection(self):
for quota in (2, 3):
def test_incubator_batch_keeps_one_primary_and_same_id_after_collection(self):
for quota in (0, 2, 3):
with self.subTest(quota=quota):
self.setUp()
rows = [graded_monster(self.catalog, mid, "CCCC", process=2, roomId=None) for mid in (1, 2, 3)]
self.snapshot.raw["stacks"] = [{"id": mid, "position": mid - 1, "monsterId": mid} for mid in (1, 2, 3)]
actions = self.plan(rows, self.policy(count=quota))
collected = {mid for a in actions if a.kind == "collect" for data in a.payload["datas"] for mid in data["monsterId"]}
self.assertEqual(collected, set(range(1, quota + 1)))
self.assertEqual(self.planner.retained, collected)
for row in rows:
row.update(process=3, roomId=1)
actions = self.plan(rows, self.policy(count=quota))
self.assertEqual(self.planner.retained, collected)
self.assertFalse(any(a.kind == "collect" for a in actions))
sold = {mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]}
self.assertEqual(sold, set(range(1, 4)) - collected)
self.assertEqual(sold, {2, 3})
self.assertEqual(self.planner.retained, {1})
rows = rows[:1]
self.snapshot.raw["stacks"] = self.snapshot.raw["stacks"][:1]
actions = self.plan(rows, self.policy(count=quota))
collected = {mid for a in actions if a.kind == "collect" for data in a.payload["datas"] for mid in data["monsterId"]}
self.assertEqual(collected, {1})
rows[0].update(process=3, roomId=1)
self.snapshot.raw["stacks"][0]["monsterId"] = 0
actions = self.plan(rows, self.policy(count=quota))
self.assertEqual(self.planner.retained, collected)
self.assertFalse(actions)
self.assertTrue(all(mid not in collected for a in actions for mid in a.payload.get("foods", [])))
def test_ranch_and_incubator_share_quota_before_and_after_collection(self):
def test_ranch_primary_rejects_equal_incubator_extras_before_and_after_collection(self):
ranch = graded_monster(self.catalog, 1, "CCCC")
rows = [ranch] + [graded_monster(self.catalog, mid, "CCCC", process=2, roomId=None) for mid in (2, 3, 4)]
self.snapshot.raw["stacks"] = [{"id": mid, "position": mid - 1, "monsterId": mid} for mid in (2, 3, 4)]
actions = self.plan(rows, self.policy(count=2))
collected = {mid for a in actions if a.kind == "collect" for data in a.payload["datas"] for mid in data["monsterId"]}
self.assertEqual(collected, {2})
self.assertEqual(self.planner.retained, {1, 2})
self.assertEqual(collected, set())
self.assertEqual(self.planner.retained, {1})
self.assertEqual([mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]], [2, 3, 4])
for row in rows[1:]:
row.update(process=3, roomId=1)
actions = self.plan(rows, self.policy(count=2))
self.assertEqual(self.planner.retained, {1, 2})
self.assertEqual([mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]], [3, 4])
self.assertEqual(self.planner.retained, {1})
self.assertEqual([mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]], [2, 3, 4])
def test_initial_incubator_quota_prefers_best_quality_last_in_raw(self):
def test_initial_incubator_keeps_first_primary_and_best_quality_backup_last_in_raw(self):
rows = [graded_monster(self.catalog, mid, "CCCC", process=2, roomId=None) for mid in (1, 2)]
rows.append(graded_monster(self.catalog, 3, "SSAS", process=2, roomId=None))
self.snapshot.raw["stacks"] = [{"id": mid, "position": mid - 1, "monsterId": mid} for mid in (1, 2, 3)]
actions = self.plan(rows, self.policy(count=2))
collected = {mid for a in actions if a.kind == "collect" for data in a.payload["datas"] for mid in data["monsterId"]}
self.assertEqual(collected, {1, 3})
self.assertEqual(collected, set())
self.assertEqual([mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]], [2])
self.assertEqual(self.planner.retained, {1, 3})
rows = [rows[0], rows[2]]
self.snapshot.raw["stacks"] = [self.snapshot.raw["stacks"][0], self.snapshot.raw["stacks"][2]]
actions = self.plan(rows, self.policy(count=2))
self.assertEqual([mid for a in actions if a.kind == "collect" for data in a.payload["datas"] for mid in data["monsterId"]], [1])
rows[0].update(process=3, roomId=1)
self.snapshot.raw["stacks"][0]["monsterId"] = 0
actions = self.plan(rows, self.policy(count=2))
self.assertEqual([mid for a in actions if a.kind == "collect" for data in a.payload["datas"] for mid in data["monsterId"]], [3])
rows[1].update(process=3, roomId=1)
self.snapshot.raw["stacks"][1]["monsterId"] = 0
actions = self.plan(rows, self.policy(count=2))
self.assertEqual(self.planner.representatives["1001010"]["id"], 1)
self.assertEqual(self.planner.retained, {1, 3})
self.assertFalse(actions)
def test_incubator_quota_quality_prevents_equal_quality_extra_retention(self):
rows = [graded_monster(self.catalog, 1, "AASA")]
@@ -125,8 +146,16 @@ class RanchRetentionTests(unittest.TestCase):
actions = self.plan(rows, self.policy(count=2))
self.assertEqual(self.planner.retained, {1, 2})
collected = [mid for a in actions if a.kind == "collect" for data in a.payload["datas"] for mid in data["monsterId"]]
self.assertEqual(collected, [2])
self.assertEqual([mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]], [])
self.assertEqual(collected, [])
self.assertEqual([mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]], [3])
rows = rows[:2]
self.snapshot.raw["stacks"] = self.snapshot.raw["stacks"][:1]
actions = self.plan(rows, self.policy(count=2))
self.assertEqual([mid for a in actions if a.kind == "collect" for data in a.payload["datas"] for mid in data["monsterId"]], [2])
rows[1].update(process=3, roomId=1)
self.snapshot.raw["stacks"][0]["monsterId"] = 0
actions = self.plan(rows, self.policy(count=2))
self.assertFalse(actions)
def test_zero_quota_still_protects_better_incubator_above_locked_ranch(self):
locked = graded_monster(self.catalog, 1, "AASA", lock=1)
@@ -159,7 +188,7 @@ class RanchRetentionTests(unittest.TestCase):
rows = [target, graded_monster(self.catalog, 2, "CCCC"), graded_monster(self.catalog, 3, "CCCC")]
self.assertEqual(self.plan(rows, self.policy(action="feed"))[0].payload, {"targetId": 1, "foods": [2, 3]})
target.update(tpLevel=4, tpExp=self.catalog.data["game_setting"]["tpExp"]["1"]["4"])
self.assertFalse(any(a.kind == "feed" and 1 in a.payload["foods"] for a in self.plan(rows, self.policy(action="feed"))))
self.assertFalse(any(a.kind == "feed" for a in self.plan(rows, self.policy(action="feed"))))
def test_normal_cap_still_allows_tp_food_until_cumulative_exp_is_full(self):
target = graded_monster(self.catalog, 1, "SCCC", level=10, tpLevel=2, tpExp=6,
@@ -171,9 +200,9 @@ class RanchRetentionTests(unittest.TestCase):
target["tpExp"] = self.catalog.data["game_setting"]["tpExp"]["1"]["4"]
self.assertFalse(any(a.kind == "feed" for a in self.plan([target, food], self.policy(action="feed"))))
def test_unmanaged_protected_and_other_feed_targets_are_not_materials(self):
def test_unmanaged_other_species_primary_and_locked_monsters_are_not_materials(self):
target = graded_monster(self.catalog, 1, "SSSS", tpLevel=0, tpExp=0)
other = graded_monster(self.catalog, 2, "SSSA", tpLevel=0, tpExp=0)
other = graded_monster(self.catalog, 2, "SSSA", species=1002010, tpLevel=0, tpExp=0)
food = graded_monster(self.catalog, 3, "SSSB")
action = self.plan([target, other, food], self.policy(action="feed", count=0), managed=[3])[0]
self.assertEqual(action.payload, {"targetId": 1, "foods": [3]})
@@ -199,9 +228,9 @@ class RanchRetentionTests(unittest.TestCase):
def test_missing_tp_fields_pause_special_feed_but_not_legacy_experience(self):
target = graded_monster(self.catalog, 1, "SCCC", level=10,
potentialLevel=1, exp=self.catalog.data["monster_level"]["10"])
food = graded_monster(self.catalog, 2, "CCCC")
food = graded_monster(self.catalog, 2, "CCCC", level=1)
self.assertFalse(any(a.kind == "feed" for a in self.plan([target, food], self.policy(action="feed"))))
target.update(tpLevel=0, tpExp=0, level=1, exp=0)
target.update(tpLevel=0, tpExp=0, level=2, exp=0)
policy = Policy(strategy="experience", feed_target=1, fill=False, protect_star=6, protect_quality=6)
self.assertEqual(self.plan([target, food], policy)[0].payload, {"targetId": 1, "foods": [2]})
@@ -41,7 +41,10 @@ class ManualRuleTests(unittest.TestCase):
self.planner.managed.add(food["id"])
primary = self.snapshot.monsters[900]
primary.update(potentialLevel=2, level=20)
secondary = dict(primary, id=901, level=9, potentialLevel=1)
row = self.catalog.monster(primary["typeId"])
for stat in ("atk", "def", "hp", "dex"):
primary["g" + stat.capitalize()] = row[stat + "_grow_min"] + .6 * (row[stat + "_grow_max"] - row[stat + "_grow_min"])
secondary = dict(primary, id=901, typeId=1002010, level=9, potentialLevel=1)
self.snapshot.raw["monsters"].append(secondary)
policy = Policy(manual_eggs=True, strategy="gold", fill=False, protect_star=6, protect_quality=5,
egg_rules={str(food["typeId"]): self.rule(action="feed", keep_count=0)}, feed_targets={"900": 1, "901": 2})
@@ -0,0 +1,479 @@
"""Offline regressions for primary-only cultivation and bounded species retention."""
import copy
from dataclasses import asdict
import unittest
from ranch_assistant.cultivation import quality_rank
from ranch_assistant.model import Action, Catalog, EggRule, Planner, Policy, Snapshot
SPECIES = 1030010
class SpeciesRetentionLimitsTests(unittest.TestCase):
def setUp(self):
self.catalog = Catalog()
room_type = next(iter(self.catalog.data["room_info"]))
self.catalog.data["room_info"][room_type]["maxNum"] = 20
self.snapshot = Snapshot({"master": {"id": 1}, "monsters": [], "teams": [],
"stacks": [], "items": [], "rooms": [{"id": 1, "typeId": int(room_type)},
{"id": 2, "typeId": int(room_type)}]})
self.planner = Planner(self.catalog)
def mon(self, mid, grades="CCCC", *, species=SPECIES, **values):
info = self.catalog.monster(species)
mon = {"id": mid, "typeId": species, "process": 3, "mode": 2,
"level": 10, "feel": 0, "roomId": 1, "potentialLevel": 3,
"exp": 451, "tpLevel": 0, "tpExp": 0, "lock": 0}
for stat, grade in zip(("atk", "def", "hp", "dex"), grades):
low, high = info[stat + "_grow_min"], info[stat + "_grow_max"]
mon["g" + stat.capitalize()] = low + (high - low) * {
"C": .1, "B": .375, "A": .625, "S": .9}[grade]
return mon | values
def policy(self, *, action="sell", count=1, **values):
return Policy(**({"manual_eggs": True, "fill": False, "buy": False,
"protect_star": 6, "protect_quality": 5, "keep_better_quality": False,
"gift_auto_representative": True, "egg_rules": {str(SPECIES):
asdict(EggRule(enabled=True, action=action, keep_count=count))}} | values))
def plan(self, rows, policy=None, *, managed=()):
self.snapshot.raw["monsters"] = rows
self.planner.managed.update(managed)
return self.planner.plan(self.snapshot, policy or self.policy())
@staticmethod
def sold(actions):
return {mid for action in actions if action.kind == "sell"
for mid in action.payload["monsterIds"]}
@staticmethod
def collected(actions):
return {mid for action in actions if action.kind == "collect"
for data in action.payload["datas"] for mid in data["monsterId"]}
def screenshot(self):
return [self.mon(910001, "SASS", level=20, potentialLevel=2,
tpLevel=4, tpExp=999, exp=self.catalog.data["monster_level"]["20"], lock=1),
self.mon(910002, "SASA"), self.mon(910003, "AASS"),
self.mon(910004, "SASA"), self.mon(910005, "ASAS", level=9)]
def test_screenshot_unmanaged_extras_are_trimmed_only_for_enabled_species(self):
rows = self.screenshot()
unrelated = self.mon(999, "SSSS", species=1030012)
actions = self.plan(rows + [unrelated])
self.assertEqual(self.sold(actions), {row["id"] for row in rows[1:]})
self.assertEqual(self.planner.retained, {910001})
self.assertFalse(any(action.kind == "feed" for action in actions))
self.assertFalse(self.planner.managed, "Planning must not invent recorded ownership")
def test_screenshot_tp_and_ordinary_caps_never_fall_back_to_duplicate(self):
rows = self.screenshot()
self.snapshot.raw["monsters"] = rows
self.planner.managed.update(row["id"] for row in rows[1:])
target, _ = self.planner.same_species_feeding_target(rows[-1], self.snapshot,
self.policy(action="feed"))
self.assertIsNone(target)
self.assertFalse(any(action.kind == "feed" for action in
self.plan(rows, self.policy(action="feed"))))
def test_old_keep_flags_and_counts_do_not_expand_or_disable_fixed_slots(self):
for count in (0, 1, 2, 1000):
for keep_better in (False, True):
with self.subTest(count=count, keep_better=keep_better):
self.setUp()
rows = [self.mon(1, "AASA", level=30), self.mon(2, "SSAS"),
self.mon(3, "SSAS", roomId=2), self.mon(4, "AASA")]
policy = self.policy(count=count, keep_better_quality=keep_better)
before = copy.deepcopy(asdict(policy))
actions = self.plan(rows, policy)
self.assertEqual(self.planner.retained, {1, 2})
self.assertEqual(self.sold(actions), {3, 4})
self.assertEqual(asdict(policy), before)
def test_quality_protection_does_not_keep_unlimited_managed_four_s(self):
for threshold in (3, 6):
with self.subTest(threshold=threshold):
self.setUp()
rows = [self.mon(1, "SSSS", level=30)] + [
self.mon(mid, "SSSS") for mid in (2, 3, 4)]
actions = self.plan(rows, self.policy(count=1000, protect_quality=threshold),
managed=(1, 2, 3, 4))
self.assertEqual(self.planner.retained, {1})
self.assertEqual(self.sold(actions), {2, 3, 4})
def test_backup_requires_strict_improvement_over_primary(self):
rows = [self.mon(1, "SSAS", level=30), self.mon(2, "SSAS"), self.mon(3, "AASA")]
self.assertEqual(self.sold(self.plan(rows)), {2, 3})
self.assertEqual(self.planner.retained, {1})
def test_equal_four_s_newcomer_dispatches_instead_of_becoming_tp_food(self):
primary = self.mon(1, "SSSS", level=30, tpLevel=0, tpExp=0)
newcomer = self.mon(2, "SSSS", process=2, roomId=None)
self.snapshot.raw["stacks"] = [{"id": 1, "position": 0, "monsterId": 2}]
policy = self.policy(action="feed")
actions = self.plan([primary, newcomer], policy)
self.assertEqual(self.sold(actions), {2})
self.assertEqual(self.collected(actions), set())
newcomer.update(process=3, roomId=1)
actions = self.plan([primary, newcomer], policy)
self.assertEqual(self.sold(actions), {2})
self.assertFalse(any(a.kind == "feed" for a in actions))
def test_rejected_better_quality_candidate_dispatches_and_hard_locks_still_win(self):
for protected in (False, True):
with self.subTest(protected=protected):
self.setUp()
rows = [self.mon(1, "AASA", level=30), self.mon(2, "SSSS"),
self.mon(3, "SSAS", lock=int(protected))]
policy = self.policy(action="feed")
actions = self.plan(rows, policy, managed=(2, 3))
self.assertEqual(self.sold(actions), set() if protected else {3})
self.assertEqual(self.planner.disposition(rows[2], self.snapshot, policy),
"keep" if protected else "sell")
self.assertFalse(any(a.kind == "feed" for a in actions))
def test_backup_ranks_s_count_before_equal_weight_normalized_growth(self):
rows = [self.mon(1, "CCCC", level=30), self.mon(2, "AAAC"),
self.mon(3, "BBAA"), self.mon(4, "SSAS"), self.mon(5, "AASA")]
self.assertGreater(quality_rank(self.catalog, rows[3]), quality_rank(self.catalog, rows[4]))
self.assertEqual(self.sold(self.plan(rows)), {2, 3, 5})
self.assertEqual(self.planner.retained, {1, 4})
def test_backup_breaks_grade_ties_by_equal_weight_normalized_growth(self):
primary = self.mon(1, level=30)
better_atk, better_hp = self.mon(2, "AAAA"), self.mon(3, "AAAA")
info = self.catalog.monster(SPECIES)
better_atk["gAtk"] += .05 * (info["atk_grow_max"] - info["atk_grow_min"])
better_hp["gHp"] += .10 * (info["hp_grow_max"] - info["hp_grow_min"])
self.assertEqual(self.sold(self.plan([primary, better_atk, better_hp])), {2})
self.assertEqual(self.planner.retained, {1, 3})
def test_equal_s_count_uses_growth_without_extra_a_or_b_count_priority(self):
rows = [self.mon(1, level=30), self.mon(2, "SACC"), self.mon(3, "SBBB")]
self.assertLess(quality_rank(self.catalog, rows[1]), quality_rank(self.catalog, rows[2]))
self.assertEqual(self.sold(self.plan(rows)), {2})
self.assertEqual(self.planner.retained, {1, 3})
def test_quality_tie_prefers_existing_ranch_backup_over_new_incubator(self):
primary, backup = self.mon(1, level=30), self.mon(20, "SSAS")
self.plan([primary, backup])
new = self.mon(10, "SSAS", process=2, roomId=None)
self.snapshot.raw["stacks"] = [{"id": 1, "position": 0, "monsterId": 10}]
actions = self.plan([new, backup, primary])
self.assertEqual(self.planner.retained, {1, 20})
self.assertEqual(self.sold(actions), {10})
self.assertEqual(self.collected(actions), set())
def test_equal_ranch_backups_use_oldest_id_independent_of_row_order(self):
for order in ((30, 20, 10), (10, 30, 20)):
with self.subTest(order=order):
self.setUp()
rows = [self.mon(1, level=30)] + [self.mon(mid, "SSAS") for mid in order]
self.assertEqual(self.sold(self.plan(rows)), {20, 30})
self.assertEqual(self.planner.retained, {1, 10})
def test_better_incubator_dispatches_obsolete_backup_before_collection(self):
primary, old = self.mon(1, level=30), self.mon(2, "SSAS")
self.plan([primary, old])
new = self.mon(3, "SSSS", process=2, roomId=None)
self.snapshot.raw["stacks"] = [{"id": 1, "position": 0, "monsterId": 3}]
policy = self.policy(action="feed")
actions = self.plan([primary, old, new], policy, managed=(2, 3))
self.assertEqual(self.sold(actions), {2})
self.assertEqual(self.collected(actions), set())
self.assertFalse(any(action.kind == "feed" for action in actions))
actions = self.plan([primary, new], policy)
self.assertEqual(self.collected(actions), {3})
self.assertEqual(self.sold(actions), set())
def test_obsolete_backup_replacement_waits_when_dispatch_is_off(self):
rows = [self.mon(1, level=30), self.mon(2, "SSAS"),
self.mon(3, "SSSS", process=2, roomId=None)]
actions = self.plan(rows, self.policy(dispatch=False), managed=(2, 3))
self.assertEqual(actions, [])
self.assertIn("派遣", self.planner.statuses[2])
self.assertIn("关闭", self.planner.statuses[2])
def test_first_mature_incubator_is_collected_before_any_feeding(self):
rows = [self.mon(2, "SSSS", process=2, roomId=None),
self.mon(1, process=2, roomId=None)]
self.snapshot.raw["stacks"] = [{"id": mid, "position": mid - 1,
"monsterId": mid} for mid in (1, 2)]
actions = self.plan(rows, self.policy(action="feed"))
self.assertEqual(self.collected(actions), {1})
self.assertFalse(any(action.kind == "feed" for action in actions))
self.assertIn(1, self.planner.retained)
def test_primary_can_consume_only_nonprotected_lower_quality_excess(self):
rows = [self.mon(1, "AAAA", level=30, lock=1), self.mon(2, "SSSS"), self.mon(3)]
actions = self.plan(rows, self.policy(action="feed"), managed=(2, 3))
self.assertEqual([a.payload for a in actions if a.kind == "feed"],
[{"targetId": 1, "foods": [3]}])
self.assertEqual(self.planner.retained, {1, 2})
def test_legacy_same_species_feed_does_not_require_target_quality_above_fodder(self):
rows = [self.mon(1, level=30, lock=1), self.mon(2, "SSAS")]
policy = Policy(strategy="experience", fill=False, protect_star=6, protect_quality=5)
actions = self.plan(rows, policy, managed=(2,))
self.assertEqual([a.payload for a in actions if a.kind == "feed"],
[{"targetId": 1, "foods": [2]}])
def test_backup_is_food_protected_but_never_a_target(self):
primary = self.mon(1, level=30, tpLevel=4, tpExp=999)
backup, food = self.mon(2, "SSSS"), self.mon(3, "SSAS")
self.snapshot.raw["monsters"] = [primary, backup, food]
self.planner.managed.update((2, 3))
policy = self.policy(action="feed")
self.assertTrue(self.planner.protected(backup, self.snapshot, policy))
target, reason = self.planner.same_species_feeding_target(food, self.snapshot, policy)
self.assertIsNone(target, reason)
self.assertNotIn(2, self.planner.tp_feed_targets)
def test_same_species_selection_uses_only_primary_even_if_priority_favors_backup(self):
primary, backup, food = self.mon(1, level=30), self.mon(2, "SSSS"), self.mon(3, "SSAS")
self.snapshot.raw["monsters"] = [primary, backup, food]
self.planner.managed.update((2, 3))
policy = self.policy(action="feed", breakthrough_targets={"2": 1})
target, _ = self.planner.same_species_feeding_target(food, self.snapshot, policy)
self.assertIs(target, primary)
def test_unavailable_primary_does_not_fall_back_to_available_duplicate(self):
for unavailable in ({"inExploreTeam": True}, {"inBuild": True}):
with self.subTest(unavailable=unavailable):
self.setUp()
rows = [self.mon(1, level=30, **unavailable), self.mon(2, "SSSS"), self.mon(3, "SSAS")]
self.snapshot.raw["monsters"] = rows
self.planner.managed.update((2, 3))
policy = self.policy(action="feed", feed_targets={"1": 1, "2": 2})
self.assertIsNone(self.planner.feeding_target(self.snapshot, policy)[0])
self.assertIsNone(self.planner.same_species_feeding_target(rows[-1], self.snapshot, policy)[0])
def test_manual_backup_only_is_skipped_without_changing_selection(self):
rows = [self.mon(1, level=30), self.mon(2, "SSSS"), self.mon(3, "SSAS")]
for values in ({"feed_targets": {"2": 1}}, {"feed_target": 2}):
with self.subTest(values=values):
self.snapshot.raw["monsters"] = rows
policy = self.policy(action="feed", **values)
before = copy.deepcopy(asdict(policy))
target, reason = self.planner.feeding_target(self.snapshot, policy)
self.assertIsNone(target)
self.assertIn("主培养", reason)
self.assertIn("#1", reason)
self.assertFalse(any(action.kind == "feed" for action in
self.plan(rows, policy, managed=(2, 3))))
self.assertEqual(asdict(policy), before)
def test_manual_capped_primary_skips_duplicate_and_may_use_other_species_primary(self):
rows = [self.mon(1, level=30), self.mon(2, "SSSS"), self.mon(3, species=1002010)]
self.snapshot.raw["monsters"] = rows
policy = self.policy(feed_targets={"1": 1, "2": 2, "3": 3})
self.assertIs(self.planner.feeding_target(self.snapshot, policy)[0], rows[2])
del policy.feed_targets["3"]
self.assertIsNone(self.planner.feeding_target(self.snapshot, policy)[0])
def test_all_hard_protections_survive_species_limit(self):
flags = ({"lock": 1}, {"sysLock": 1}, {"equip1": 7}, {"entangle": 1},
{"inExploreTeam": 1}, {"inBuild": 1}, {"gAtk": None})
rows = [self.mon(1, level=30)] + [self.mon(mid, "SSAS", **values)
for mid, values in enumerate(flags, 2)]
rows += [self.mon(20, "SSAS"), self.mon(21, "CCCC")]
self.snapshot.raw["teams"] = [{"id": 1, "monsters": [20]}]
before = copy.deepcopy(rows)
actions = self.plan(rows, managed=range(1, 22))
self.assertEqual(self.sold(actions), {21})
self.assertEqual(rows, before)
for row in rows[1:-1]:
self.assertIn("保护", self.planner.statuses[row["id"]])
def test_reserved_species_never_sells_or_feeds_extras(self):
rows = [self.mon(1, level=30), self.mon(2, "SSAS"), self.mon(3)]
actions = self.plan(rows, self.policy(reserved_types=[SPECIES]), managed=(2, 3))
self.assertFalse(any(a.kind in ("sell", "feed") for a in actions))
self.assertIn("委托", self.planner.statuses[3])
def test_active_exploration_roster_protects_extras_without_individual_flags(self):
for members in ("910002", [910002], (910002,)):
with self.subTest(members=members):
self.setUp()
rows = self.screenshot()
# Status remains occupied until exploration rewards are claimed,
# including when its end time has already passed.
self.snapshot.raw["exploreTeams"] = [{"id": 7, "status": 1,
"monsters": members, "endTime": 1}]
actions = self.plan(rows, self.policy(action="feed"),
managed=tuple(row["id"] for row in rows))
self.assertEqual(self.sold(actions), {910003, 910004, 910005})
self.assertEqual(self.planner.retained, {910001, 910002})
self.assertIn("保护", self.planner.statuses[910002])
self.assertFalse(any(a.kind == "feed" for a in actions))
def test_exploring_primary_without_individual_flag_is_never_feed_target(self):
rows = self.screenshot()
rows[0].update(level=19, exp=451, tpLevel=0, tpExp=0)
self.snapshot.raw["monsters"] = rows
self.snapshot.raw["exploreTeams"] = [{"id": 7, "status": "1",
"monsters": "910001"}]
self.planner.managed.update(row["id"] for row in rows[1:])
policy = self.policy(action="feed", feed_targets={"910001": 1})
self.assertIsNone(self.planner.feeding_target(self.snapshot, policy)[0])
self.assertIsNone(self.planner.same_species_feeding_target(rows[1], self.snapshot, policy)[0])
action = Action("feed", "busy primary", "monsterService/monsterIntensify",
{"targetId": 910001, "foods": [910002]})
self.assertEqual(self.planner.batch_actions([action], self.snapshot, policy), [])
def test_exploration_only_changes_invalidate_retention_cache(self):
rows = self.screenshot()
self.snapshot.raw["monsters"] = rows
policy = self.policy()
self.assertFalse(self.planner.protected(rows[1], self.snapshot, policy))
self.snapshot.raw["exploreTeams"] = [{"id": 7, "status": 1,
"monsters": [910002]}]
self.assertTrue(self.planner.protected(rows[1], self.snapshot, policy))
self.assertIn(910002, self.planner.retained)
self.snapshot.raw["exploreTeams"][0]["status"] = 0
self.assertFalse(self.planner.protected(rows[1], self.snapshot, policy))
self.assertNotIn(910002, self.planner.retained)
def test_dispatch_off_reports_unmanaged_extras_without_expanding_ownership(self):
rows = self.screenshot()
self.assertEqual(self.plan(rows, self.policy(dispatch=False)), [])
self.assertIn("关闭", self.planner.statuses[910002])
self.assertFalse(self.planner.managed)
def test_disabled_rules_and_disabled_automation_never_adopt_old_inventory(self):
rows = self.screenshot()
for policy in (self.policy(enabled=False), self.policy(egg_rules={str(SPECIES):
asdict(EggRule(enabled=False))})):
with self.subTest(policy=policy):
self.assertEqual(self.plan(rows, policy), [])
self.assertFalse(self.planner.managed)
def test_stale_nonprimary_targets_do_not_override_species_slots(self):
rows = [self.mon(1, level=30), self.mon(2, "SSSS"), self.mon(3, "SSAS"), self.mon(4)]
policy = self.policy(action="feed", feed_targets={"3": 1}, breakthrough_targets={"4": 1})
actions = self.plan(rows, policy, managed=(2, 3, 4))
self.assertEqual(self.sold(actions), {3, 4})
self.assertFalse(any(a.kind == "feed" for a in actions))
self.assertFalse(self.planner.protected(rows[2], self.snapshot, policy))
self.assertFalse(self.planner.protected(rows[3], self.snapshot, policy))
def test_all_old_targets_and_star_threshold_are_soft_for_enabled_species(self):
rows = self.screenshot()
rows[2]["lock"] = 1
selected = {str(row["id"]): i for i, row in enumerate(rows, 1)}
policy = self.policy(action="feed", protect_star=1, feed_targets=selected.copy(),
gift_targets=selected.copy(), breakthrough_targets=selected.copy())
before = copy.deepcopy(asdict(policy))
actions = self.plan(rows, policy, managed=tuple(row["id"] for row in rows))
self.assertEqual(self.sold(actions), {910002, 910004, 910005})
self.assertEqual(self.planner.retained, {910001, 910003})
self.assertIn("保护", self.planner.statuses[910003])
self.assertEqual(asdict(policy), before)
self.assertFalse(any(a.kind == "feed" for a in actions))
def test_batch_revalidates_primary_instead_of_trusting_supplied_feed_action(self):
rows = [self.mon(1, level=30), self.mon(2, "SSSS"), self.mon(3, "SSAS")]
self.snapshot.raw["monsters"] = rows
self.planner.managed.update((2, 3))
action = Action("feed", "stale duplicate target", "monsterService/monsterIntensify",
{"targetId": 2, "foods": [3]})
self.assertEqual(self.planner.batch_actions([action], self.snapshot,
self.policy(action="feed", feed_targets={"2": 1})), [])
def test_batch_never_consumes_primary_backup_unmanaged_or_locked_food(self):
rows = [self.mon(1, "AAAA", level=29), self.mon(2, "SSSS"), self.mon(3),
self.mon(4, lock=1), self.mon(5, species=1002010)]
self.snapshot.raw["monsters"] = rows
self.planner.managed.update((2, 3, 4))
policy = self.policy(action="feed", feed_targets={"1": 1})
actions = [Action("feed", "candidate", "monsterService/monsterIntensify",
{"targetId": 1, "foods": [mid]}) for mid in (1, 2, 3, 4, 5)]
self.assertEqual([a.payload for a in self.planner.batch_actions(actions, self.snapshot, policy)],
[{"targetId": 1, "foods": [3]}])
def test_normal_experience_cap_still_allows_same_species_tp_on_primary(self):
rows = [self.mon(1, "AAAA", level=30, tpLevel=2, tpExp=3), self.mon(2, "SSSS"), self.mon(3)]
actions = self.plan(rows, self.policy(action="feed"), managed=(2, 3))
self.assertEqual([a.payload for a in actions if a.kind == "feed"], [{"targetId": 1, "foods": [3]}])
def test_keep_action_cannot_bypass_the_two_species_slots(self):
rows = [self.mon(1, level=30), self.mon(2, "SSSS"), self.mon(3, "SSAS"), self.mon(4)]
actions = self.plan(rows, self.policy(action="keep", count=1000))
self.assertEqual(self.sold(actions), {3, 4})
self.assertEqual(self.planner.retained, {1, 2})
def test_transient_food_collection_reserves_only_one_species_slot(self):
rows = [self.mon(1, "SSAS", level=30)] + [
self.mon(mid, process=2, roomId=None) for mid in (2, 3, 4, 5)]
self.snapshot.raw["stacks"] = [{"id": mid, "position": mid - 2,
"monsterId": mid} for mid in (2, 3, 4, 5)]
actions = self.plan(rows, self.policy(action="feed"))
self.assertEqual(self.sold(actions), {3, 4, 5})
self.assertEqual(self.collected(actions), set())
rows = rows[:2]
self.snapshot.raw["stacks"] = self.snapshot.raw["stacks"][:1]
actions = self.plan(rows, self.policy(action="feed"))
self.assertEqual(len(self.collected(actions)), 1)
self.assertEqual(self.collected(actions), {2})
self.assertTrue(all(action.kind != "feed" for action in actions))
# A refreshed snapshot sees one transient food, never four admitted at once.
rows[1].update(process=3, roomId=1)
self.snapshot.raw["stacks"][0]["monsterId"] = 0
actions = self.plan(rows, self.policy(action="feed"))
self.assertEqual(self.collected(actions), set())
self.assertTrue(any(action.kind == "feed" and action.payload["targetId"] == 1 for action in actions))
def test_primary_and_backup_block_extra_food_collection(self):
rows = [self.mon(1, "AAAA", level=30), self.mon(2, "SSSS"),
self.mon(3, process=2, roomId=None)]
self.snapshot.raw["stacks"] = [{"id": 1, "position": 0, "monsterId": 3}]
actions = self.plan(rows, self.policy(action="feed"))
self.assertEqual(self.collected(actions), set())
self.assertEqual(self.sold(actions), {3})
def test_hard_protected_old_backup_blocks_replacement_at_two_ranch_members(self):
rows = [self.mon(1, level=30), self.mon(2, "SSAS", lock=1),
self.mon(3, "SSSS", process=2, roomId=None)]
actions = self.plan(rows, managed=(2, 3))
self.assertEqual(actions, [])
self.assertIn("保护", self.planner.statuses[2])
self.assertIn("两只", self.planner.statuses[3])
def test_unknown_primary_quality_pauses_cleanup_until_synchronized(self):
rows = [self.mon(1, level=30, gAtk=None), self.mon(2, "SSSS"), self.mon(3, "SSAS")]
actions = self.plan(rows, managed=(1, 2, 3))
self.assertFalse(any(a.kind in ("sell", "feed") for a in actions))
self.assertIn("同步", self.planner.statuses[3])
def test_saved_nonranch_primary_is_held_instead_of_promoting_backup(self):
primary, backup = self.mon(30, level=30), self.mon(10, "SSSS")
self.plan([primary, backup])
primary.update(process=2, mode=1, roomId=None)
actions = self.plan([backup, primary], self.policy(action="feed"), managed=(10, 30))
self.assertEqual(self.planner.cultivation.select(self.snapshot), {})
self.assertIs(self.planner.representatives[str(SPECIES)], primary)
self.assertIn(30, self.planner.retained)
self.assertFalse(any(a.kind in ("feed", "sell", "collect") for a in actions))
self.assertIn("主培养", self.planner.statuses[10])
def test_confirmed_removed_primary_allows_selector_to_choose_new_primary(self):
primary, backup = self.mon(30, level=30), self.mon(10, "SSSS")
self.plan([primary, backup])
self.assertEqual(self.plan([backup], self.policy(action="feed"), managed=(10,)), [])
self.assertIs(self.planner.representatives[str(SPECIES)], backup)
self.assertEqual(self.planner.retained, {10})
def test_ordinary_cross_species_feed_farming_and_priorities_still_work(self):
first = self.mon(1, "SSSS", level=30, species=1002010)
second = self.mon(2, "SSSS", level=20, potentialLevel=3, species=1003010)
foods = [self.mon(mid, species=1001010, level=1, exp=0) for mid in (3, 4, 5)]
policy = Policy(strategy="experience", protect_star=6, protect_quality=5,
fill=False, feed_targets={"1": 1, "2": 2})
actions = self.plan([first, second] + foods, policy, managed=(3, 4, 5))
self.assertEqual([a.payload for a in actions if a.kind == "feed"],
[{"targetId": 2, "foods": [3, 4, 5]}])
if __name__ == "__main__":
unittest.main()
+8 -4
View File
@@ -1,8 +1,8 @@
# 牧羊人之心牧场助手 · Web 2.0.6
# 牧羊人之心牧场助手 · Web 2.0.7
## 产品约束
把现有桌面助手的功能和操作结构迁移至单管理员 Web 工作台。桌面版是页面顺序、信息密度、业务名称、保护条件与交互的依据,保留桌面兼容。本轮 Web 发布目标为 `2.0.6`,源码入口 `main`,游戏数据版本 `1.9.68`;桌面正式版保留 `1.2.0`。启动与配置见 [运行说明](README.md),Docker 与更新条件见 [部署说明](../deploy/web/README.md)。
把现有桌面助手的功能和操作结构迁移至单管理员 Web 工作台。桌面版是页面顺序、信息密度、业务名称、保护条件与交互的依据,保留桌面兼容。本轮 Web 发布目标为 `2.0.7`,源码入口 `main`,游戏数据版本 `1.9.68`;桌面正式版保留 `1.2.0`。启动与配置见 [运行说明](README.md),Docker 与更新条件见 [部署说明](../deploy/web/README.md)。
使用者在 Windows 本机配置、验证,随后可在 Linux Docker 常驻运行。多个浏览器访问同一个管理员工作台;账号互相隔离,各账号串行执行,账号之间可以并行。
@@ -24,9 +24,13 @@
- 数据分析用真实 DTO 绘制 SVG 条形图,保留来源筛选、体力效率、样本和不确定性说明。没有样本时明确说明。
- 策略统一导入导出;收益 CSV/XLSX 导入与可用数据下载。错误展示具体原因,不把不支持的任务伪装成可执行任务。
- 帮助可检查 GitHub 正式版本并提交受控更新请求。未配置部署器时明确显示原因,更新提交不表示更新成功。
- 已在 2.0.1 完成私有仓库和 GHCR 认证的部署,可在 2.0.6 发布就绪后直接通过“帮助 → 检查版本更新…”升级,无需先安装 2.0.2、重复初始化或替换宿主机更新器;升级完成后刷新网页以加载新版界面,安装结果以宿主机健康检查为准。
- 已在 2.0.1 完成私有仓库和 GHCR 认证的部署,可在 2.0.7 发布就绪后直接通过“帮助 → 检查版本更新…”升级,无需先安装 2.0.2、重复初始化或替换宿主机更新器;升级完成后刷新网页以加载新版界面,安装结果以宿主机健康检查为准。
## 2.0.6 表单布局
## 2.0.7 主培养与资质备用
同种只自动培养已养成的高等级主培养;新资质更好的魔物只作为备用保留,不分配经验、礼物或潜能材料。已启用种类按主培养1只、更优备用最多1只整理,新备用严格更优才替换,同分保留已有备用。主培养到上限或冷却时等待,不向同种备用转移资源。硬保护保留,未勾选种类不扩大自动整理范围。
## 表单布局(2.0.6 起)
勾选框与右侧文字组成一组;数字、文本与下拉框采用标签在上、控件在下的布局。设置区限定合理宽度,并按可用空间排为多列,每日领取项目在单独分组中排列。界面尺寸变化不改变配置路径、自动保存或策略执行规则。
+7 -7
View File
@@ -1,6 +1,6 @@
# Web 2.0.6 运行说明
# Web 2.0.7 运行说明
本轮 Web 发布目标 **2.0.6**,源码入口 `main`,游戏资料基线 **1.9.68**。桌面正式版保留 **1.2.0**,入口为 `python -m ranch_assistant`;Web 使用独立依赖与数据根。
本轮 Web 发布目标 **2.0.7**,源码入口 `main`,游戏资料基线 **1.9.68**。桌面正式版保留 **1.2.0**,入口为 `python -m ranch_assistant`;Web 使用独立依赖与数据根。
Web 采用 FastAPI / Uvicorn 和原生 HTML/CSS/ES 模块,无 Node、npm 或前端编译步骤,不安装 PySide6。页面和策略能力沿用现有核心,详细业务范围与原有限制见 [桌面使用说明](../ranch_assistant/README.md)。多浏览器连接同一个管理员工作台;一个服务实例内,各账号独立线程并行,同一账号操作串行。
@@ -10,8 +10,8 @@ Web 采用 FastAPI / Uvicorn 和原生 HTML/CSS/ES 模块,无 Node、npm 或
- [x] 保留账号页签、顶部数值与统一启停、可调日志;规则自动保存,配置与统计按账号/角色隔离,每次成功登录后自动执行已配置且已勾选的功能,可在顶部停止。
- [x] Windows Python 启动与离线演示;Web 导入链和依赖不使用 Qt,无 Node 构建步骤。
- [x] 提供 Linux Docker 与稳定 2.x 受控更新、停机备份及失败回滚脚本;历史 Linux Docker 部署、持久化权限、健康检查和定时更新检查烟测见下文。
- [x] 本轮发布目标为 `2.0.6`,保留桌面兼容;战斗模拟为近似模型,特殊关卡并非全部支持,真实游戏 API 验收范围不因版本号变更而扩大。
- 2.0.6 统一策略表单布局,勾选框贴近标签,普通字段标签置于控件上方,每日领取项目分组排列。详见 [本版发布说明](../analysis/RELEASE_2_0_6.md)。
- [x] 本轮发布目标为 `2.0.7`,保留桌面兼容;战斗模拟为近似模型,特殊关卡并非全部支持,真实游戏 API 验收范围不因版本号变更而扩大。
- 2.0.7 修复同种重复培养:主培养与资质备用分离,自动喂养、赠礼和潜能突破仅作用于主培养,启用种类固定主培养1只与更优备用最多1只。详见 [本版发布说明](../analysis/RELEASE_2_0_7.md)。
- 2.0.3 修复 2.0.2 日志布局:所有页签复用原有底部日志区,按当前账号与功能筛选,默认收起;操作约定见 [产品说明](PRODUCT.md#203-底部分类日志),验收结果见 [发布说明](../analysis/RELEASE_2_0_3.md#验证)。
## Windows 本地运行
@@ -97,13 +97,13 @@ sh start-web.sh --no-browser
Web 检查固定官方 GitHub Releases 的稳定 `v2.x.y`,跳过桌面 1.x、未来 3.x、草稿和预发布。开发版本 `2.0.0.dev1` 可升级至同数字的正式 `v2.0.0`;没有正式 Web 2 发布时明确显示暂无更新。Windows 默认仅检查;Web “更新”按钮仅在宿主机显式启用并有有效只读心跳时可提交 `pending` 请求,安装、备份和回滚由宿主机执行。默认定时检查只通知,自动安装需操作者 opt-in。
已在 **2.0.1** 完成私有仓库和 GHCR 认证的部署,可在 2.0.6 稳定 Release 和正式镜像就绪、宿主机心跳有效后,直接通过“帮助 → 检查版本更新…”升级 **2.0.6**,无需先安装 2.0.2、重复初始化或替换宿主机更新器。升级完成后刷新网页以加载新版界面,底部日志默认收起。安装结果以宿主机健康检查为准;首次配置仅供尚未初始化的宿主机参考。
已在 **2.0.1** 完成私有仓库和 GHCR 认证的部署,可在 2.0.7 稳定 Release 和正式镜像就绪、宿主机心跳有效后,直接通过“帮助 → 检查版本更新…”升级 **2.0.7**,无需先安装 2.0.2、重复初始化或替换宿主机更新器。升级完成后刷新网页以加载新版界面,底部日志默认收起。安装结果以宿主机健康检查为准;首次配置仅供尚未初始化的宿主机参考。
## 离线验证
2.0.6 验证结果统一见 [发布说明](../analysis/RELEASE_2_0_6.md#验证),以下历史记录不计入本版验收。
2.0.7 验证结果统一见 [发布说明](../analysis/RELEASE_2_0_7.md#验证),以下历史记录不计入本版验收。
### 历史验证记录(不计入 2.0.6)
### 历史验证记录(不计入 2.0.7)
2.0.2 验证记录见 [历史发布说明](../analysis/RELEASE_2_0_2.md#验证)。
+1 -1
View File
@@ -1,6 +1,6 @@
"""Headless Web workspace for the ranch assistant."""
__version__ = "2.0.6"
__version__ = "2.0.7"
GAME_VERSION = "1.9.68"
__all__ = ["__version__", "GAME_VERSION"]
+2 -2
View File
@@ -415,7 +415,7 @@ async function exportYields(account=current()) {
async function command(name,account=current()) {
try {
if(name==='add-account'||name==='add-demo')return await addAccount(name==='add-demo');
if(name==='about')return dialog('关于牧场助手',el('div',{},el('p',{text:`牧羊人之心牧场助手 Web ${state.meta?.version || '2.0.6'}`}),el('p',{text:`游戏数据版本 ${state.meta?.gameVersion || '1.9.68'}`})),{info:true});
if(name==='about')return dialog('关于牧场助手',el('div',{},el('p',{text:`牧羊人之心牧场助手 Web ${state.meta?.version || '2.0.7'}`}),el('p',{text:`游戏数据版本 ${state.meta?.gameVersion || '1.9.68'}`})),{info:true});
if(name==='updates')return await showUpdates();
if(name==='admin-logout'){hideWorkbench();try{await api.logout();}finally{requireAuth();}return;}
if(!account)throw new Error('请先新增或选择账号。');
@@ -640,7 +640,7 @@ async function bootstrap() {
$('#app').hidden=false;
const [meta,schema]=await Promise.all([api.meta(),api.schema()]);state.meta=meta;state.schema=schema;
if(state.redirecting)return;
$('#app-version').textContent=meta.version || '2.0.6';$('#game-version').textContent=meta.gameVersion || '1.9.68';$('#access-mode').textContent=auth.access_mode==='local'||auth.access_mode==='loopback'?'本机工作台':auth.required?'管理工作台':'本机工作台';
$('#app-version').textContent=meta.version || '2.0.7';$('#game-version').textContent=meta.gameVersion || '1.9.68';$('#access-mode').textContent=auth.access_mode==='local'||auth.access_mode==='loopback'?'本机工作台':auth.required?'管理工作台':'本机工作台';
await syncAccounts();if(state.redirecting)return;state.ready=true;setStatus('工作台已连接');
}catch(failure){if(failure.status===401||$('#app').hidden){requireAuth();return;}if(state.redirecting)return;setStatus(failure.message);$('#page-host').replaceChildren(el('div',{class:'initial-state'},el('p',{text:failure.message}),el('button',{text:'重新连接',onClick:bootstrap})));}
}
+1 -1
View File
@@ -26,7 +26,7 @@
</div></details>
<details class="menu"><summary accesskey="h">帮助<span class="access-key">(H)</span></summary><div class="menu-popup"><button data-command="updates">检查版本更新…</button><button data-command="debug">调试日志</button><button data-command="about">关于…</button></div></details>
</nav>
<span class="window-title">牧羊人之心牧场助手 <span id="app-version">2.0.6</span></span>
<span class="window-title">牧羊人之心牧场助手 <span id="app-version">2.0.7</span></span>
<span id="access-mode" class="muted"></span>
</header>
<div class="account-bar"><div id="account-tabs" class="account-tabs" role="tablist" aria-label="账号"></div><button id="add-account" class="compact" title="新增账号">+ 新增账号</button></div>
+7 -4
View File
@@ -659,17 +659,20 @@ class ServiceTests(unittest.TestCase):
worker.schedule.clock = lambda: clock[0]
worker.engine.last_heartbeat = clock[0]
monsters = list(worker.engine.snapshot.monsters)
# Use the primary so the request reaches the uncertainty barrier.
species = str(worker.engine.snapshot.monsters[monsters[0]]["typeId"])
recipient = int(worker.engine.cultivation.select(worker.engine.snapshot)[species]["id"])
if kind == "gift":
# Engine overlays confirmed gift timestamps in seconds,
# while an unchanged raw server snapshot uses milliseconds.
mon = next(row for row in worker.engine.client.raw["monsters"] if row["id"] == monsters[0])
mon = next(row for row in worker.engine.client.raw["monsters"] if row["id"] == recipient)
mon["giftTime"] = 1_700_000_000_000
worker.engine.gift_planner.confirmed[monsters[0]] = {
worker.engine.gift_planner.confirmed[recipient] = {
"owner": str(worker.engine.snapshot.raw["master"]["id"]),
"type": str(mon["typeId"]), "feel": int(mon.get("feel") or 0),
"giftTime": 1_700_000_060}
action = Action(kind, "Unconfirmed gift", "monsterService/monsterSendGift",
{"monsterId": monsters[0], "itemId": 1})
{"monsterId": recipient, "itemId": 1})
elif kind == "hatch":
slot = worker.engine.client.raw["stacks"][0]
slot["monsterId"] = -1
@@ -678,7 +681,7 @@ class ServiceTests(unittest.TestCase):
worker.engine.pending_hatches = [action]
else:
action = Action(kind, "Unconfirmed feed", "monsterService/monsterIntensify",
{"targetId": monsters[0], "foods": [monsters[1]]})
{"targetId": recipient, "foods": [monsters[1]]})
before = len(FakeClient.calls)
with patch.object(worker.engine, "plans", return_value=[action]):
if kind == "hatch":
+23 -2
View File
@@ -165,17 +165,38 @@ class TaskLogTests(unittest.TestCase):
market = next(key for key, row in engine.catalog.data["markets"].items() if row.get("money", 0) > 0)
engine.policy.daily_buy_money = 1000000
engine.planner.notes = []
primary = next(iter(engine.cultivation.select(engine.snapshot).values()))
food = next(mon for mon in engine.snapshot.monsters.values()
if mon.get("process") == 3 and mon.get("typeId") == primary["typeId"]
and int(mon["id"]) != int(primary["id"]) and not mon.get("lock") and not mon.get("sysLock"))
original_post = engine.client.http.post
def consume_feed(url, data, **kwargs):
if url.endswith("monsterService/monsterIntensify"):
payload = fixtures.decode(data, engine.client.session.key)
foods = {int(mid) for mid in payload["foods"]}
engine.client.raw["monsters"] = [mon for mon in engine.client.raw["monsters"] if int(mon["id"]) not in foods]
return original_post(url, data, **kwargs)
actions = [
Action("buy", "莉莉托斯市场十连抽蛋 ×10,花费100金币", "gachaService/gachaGetEggs", {"id": market, "num": 1}),
Action("sell", "派遣 测试魔物 #1", "monsterService/monsterSell", {"monsterIds": [1]}),
Action("feed", "喂养 测试魔物 ← 素材", "monsterService/monsterIntensify", {"targetId": 1, "foods": []}),
Action("feed", "喂养 测试魔物 ← 素材", "monsterService/monsterIntensify",
{"targetId": int(primary["id"]), "foods": [int(food["id"])]}),
]
for action in actions:
with self.subTest(kind=action.kind):
worker._running = True
after = self.manager.logs(identifier, debug=True)["next"]
with patch.object(engine, "plans", return_value=[action]):
calls_before = len(fixtures.FakeClient.calls)
with patch.object(engine, "plans", return_value=[action]), \
patch.object(engine.client.http, "post", side_effect=consume_feed):
self.tick(identifier, "poll")
if action.kind == "feed":
self.assertEqual([{key: payload[key] for key in action.payload}
for _, url, payload in fixtures.FakeClient.calls[calls_before:]
if url.endswith(action.path)], [action.payload])
self.assertNotIn(int(food["id"]), engine.snapshot.monsters)
entries = self.entries(identifier, after, debug=True)
result = [row for row in entries if not row["debug"]]
self.assertEqual({row["category"] for row in result}, {"hatching"})
+7 -3
View File
@@ -82,6 +82,7 @@ import ranch_web.policies,ranch_web.views,ranch_web.actions
fields = [field for page in value["pages"] for field in page["form"]]
self.assertTrue(all(field["label"] and isinstance(field["path"], list) for field in fields))
self.assertNotIn(["policy", "feed_target"], [field["path"] for field in fields])
self.assertNotIn(["policy", "keep_better_quality"], [field["path"] for field in fields])
self.assertNotIn(["progression_policy", "battle_mode"], [field["path"] for field in fields])
self.assertEqual(dict(PAGES)["statistics"], "数据分析")
self.assertEqual(dict(PAGES)["plans"], "执行计划")
@@ -114,16 +115,19 @@ import ranch_web.policies,ranch_web.views,ranch_web.actions
if code == 5:
self.assertTrue(row["edits"]["enabled"]["disabled"])
def test_egg_keep_count_and_missing_stock_rule_bind_real_config(self):
def test_fixed_retention_display_preserves_legacy_count_and_missing_stock_rule(self):
config = deepcopy(self.worker.config)
config["policy"]["egg_rules"]["1001010"] = {"enabled": True, "keep_count": 5, "priority": 1, "market_id": "sc_city1"}
self.worker.save_config(config)
dto = self.view("bag", {"category": "eggs"})
row = next(row for row in dto["rows"] if row["id"] == "1001010")
column = next(column for column in dto["columns"] if column["key"] == "keep_count")
column = next(column for column in dto["columns"] if column["key"] == "retention_text")
self.assertEqual(column["label"], "牧场保留")
self.assertEqual(row["keep_count"], 5)
self.assertEqual(column["edit"]["path"], ["policy", "egg_rules", "{id}", "keep_count"])
self.assertEqual(row["retention_text"], "主培养1 + 更优备选≤1")
self.assertNotIn("edit", column)
self.assertNotIn("keep_count", [column["key"] for column in dto["columns"]])
self.assertEqual(self.worker.config["policy"]["egg_rules"]["1001010"]["keep_count"], 5)
self.assertTrue(row["edits"]["market_id"]["options"])
def test_add_rule_species_defaults_follow_current_market_and_desktop_fallback(self):
+41 -11
View File
@@ -55,13 +55,12 @@ def _strategy_fields(catalog):
hatch += [_policy_field("protect_star", "保留此星级及以上", "integer", min=1, max=6, group="牧场策略"),
_policy_field("protect_quality", "资质保留条件", "select", group="牧场策略", options=_options([
(4, "S及以上"), (3, "A及以上"), (2, "B及以上"), (1, "全部资质"), (5, "不按资质保留"), (6, "四项全S(4S)才保留")])),
_policy_field("keep_better_quality", "保留资质高于牧场同种培养代表的新魔物", group="牧场策略"),
_policy_field("room_id", "收取到牧场", "select", options=_options([(0, "自动选择有空位的牧场")]), group="牧场策略"),
_policy_field("reserved_types", "额外保留魔物编号", "id_list", group="牧场策略"),
_policy_field("reserved_eggs", "保留蛋数量", "id_counts", group="牧场策略"),
_policy_field("feed", "按策略喂养选定目标(受当前突破上限限制)", group="喂养策略")]
gift = [_policy_field(key, label) for key, label in (
("gift_enabled", "启用自动赠礼"), ("gift_auto_representative", "每种魔物只培养一只,自动选择培养代表"),
("gift_enabled", "启用自动赠礼"), ("gift_auto_representative", "自动选择各类主培养赠礼(关闭时按已勾选主培养)"),
("gift_liked_only", "仅赠送目标喜欢的物品"))]
quest = [_field(["quest_policy", key], label) for key, label in (
("enabled", "启用委托自动接取 / 推进 / 领奖"), ("accept", "按氪金奖励优先接取(20 → 15 → 10)"), ("allow_items", "允许提交道具(遵守保留数量)"),
@@ -234,8 +233,7 @@ def _egg_rows(dto, engine, config, query):
dto["columns"] += [_column(k, label) for k, label in (
("time_text", "培育时间"), ("sell_money", "派遣金币"), ("sell_exp", "基础经验"),
("gold_per_hour", "金币/小时"), ("exp_per_hour", "经验/小时"), ("inventory_text", "物品ID"))]
dto["columns"].append(_row_column("keep_count", "牧场保留", ["policy", "egg_rules"], min=0, max=1000,
help="已启用规则跨牧场至少保留此数量;0不保留名额,硬保护仍有效"))
dto["columns"].append(_column("retention_text", "牧场保留"))
for key in dict.fromkeys([*groups, *rules]):
info = catalog.monster(key)
if not info or search and search not in (key + str(info.get("name", ""))).casefold():
@@ -250,13 +248,14 @@ def _egg_rows(dto, engine, config, query):
**groups.get(key, {"count": 0, "inventory_ids": []}), **rule, "time_total": total, "time_text": duration(total),
"sell_money": money, "sell_exp": exp, "gold_per_hour": round(money * 3600 / total, 2), "exp_per_hour": round(exp * 3600 / total, 2),
"inventory_text": ", ".join(map(str, groups.get(key, {}).get("inventory_ids", []))),
"rule_defaults": defaults, "rule_path": ["policy", "egg_rules", key],
"rule_defaults": defaults, "rule_path": ["policy", "egg_rules", key], "retention_text": "主培养1 + 更优备选≤1",
"edits": {"market_id": _edit(["policy", "egg_rules", key, "market_id"], "select", options=options or _options([("", "金币市场无此蛋")]))}})
dto["summary"] = f"{len(dto['rows'])} 种魔物蛋规则;已启用 {sum(row['enabled'] for row in dto['rows'])} 种"
dto["summary"] = (f"{len(dto['rows'])} 种魔物蛋规则;已启用 {sum(row['enabled'] for row in dto['rows'])} 种;"
"启用规则固定主培养1 + 更优备选≤1;锁定等硬保护仍有效")
dto["form"].append(_field(["policy", "egg_rules"], "添加魔物蛋规则", "add_rule", value=None,
options=_options([(key, row.get("name", key)) for key, row in catalog.monsters.items()]), defaults=asdict(EggRule()),
defaults_by_id={key: _default_egg_rule(catalog, key, config["policy"]["market_id"]) for key in catalog.monsters},
help="可配置背包当前没有的蛋;按孵化优先级、去向、补货和牧场保留规则自动执行"))
help="可配置背包当前没有的蛋;启用规则固定主培养1 + 更优资质备选≤1,备选不接受自动喂养、赠礼或突破"))
def _bag(dto, engine, config, query):
@@ -300,6 +299,9 @@ def _bag(dto, engine, config, query):
def _ranch(dto, engine, config, query):
snapshot, catalog = engine.snapshot, engine.catalog
engine.plans() # Refresh pure planner statuses, including existing enabled-rule duplicates.
primaries = engine.cultivation.select(snapshot)
backups = engine.planner.backups
grouped = _boolean(query.get("grouped"), False)
try:
room_id = int(query.get("room_id") or 0)
@@ -315,6 +317,7 @@ def _ranch(dto, engine, config, query):
"喂养目标", "喂养优先级", "潜能阶段", "参考攻击", "参考防御", "参考生命", "参考敏捷", "好感 / 当前上限", "喜欢的物品",
"赠礼", "赠礼优先级", "自动突破目标", "突破优先级", "同种突破", "突破经验"]
dto["columns"] = [_column(key, label) for key, label in zip(keys, labels)]
dto["columns"].insert(8, _column("cultivation_role", "培养角色"))
for prefix, mapping in (("feed", "feed_targets"), ("gift", "gift_targets"), ("breakthrough", "breakthrough_targets")):
for column in dto["columns"]:
if column["key"] == prefix + "_selected":
@@ -343,24 +346,51 @@ def _ranch(dto, engine, config, query):
key = str(int(mon["id"]))
row = dict(zip(keys, values)) | {"id": key, "type_id": str(mon["typeId"]), "level": int(mon.get("level") or 1), "max_level": catalog.max_level(mon),
"process": mon.get("process"), "room_id": int(mon.get("roomId") or 0), "group": "incubator" if mon.get("process") == 2 else f"room:{int(mon.get('roomId') or 0)}", "edits": {}}
primary, backup = primaries.get(row["type_id"]), backups.get(row["type_id"])
reason = engine.cultivation_target_reason(mon["id"], primaries=primaries)
retained_primary = engine.planner.representatives.get(row["type_id"])
if primary and int(primary["id"]) == int(mon["id"]):
role, role_label = "primary", "主培养"
elif backup and int(backup["id"]) == int(mon["id"]):
role, role_label = "backup", "更优资质备选" + ("(待收取)" if mon.get("process") == 2 else "")
elif mon.get("process") == 2:
pending_primary = retained_primary and int(retained_primary["id"]) == int(mon["id"])
role, role_label = ("primary_pending", "主培养待收取") if pending_primary else ("incubator", "培育中")
else:
role, role_label = ("duplicate", "同种重复") if primary else ("unconfirmed", "主培养待确认")
row.update(cultivation_role=role_label,
cultivation_role_key=role, primary_id=int(primary["id"]) if primary else None,
automatic_eligible=not reason, automatic_reason=reason, tooltips={"cultivation_role": reason or "同种唯一自动培养对象"})
rule_enabled = engine.policy.manual_eggs and config["policy"]["egg_rules"].get(row["type_id"], {}).get("enabled")
status = engine.planner.statuses.get(int(mon["id"]), "")
if rule_enabled or int(mon["id"]) in managed:
row["scope"] = status or "启用规则管理"
if not engine.policy.enabled:
row["scope"] = "自动管理已关闭;" + row["scope"]
elif role == "duplicate" and not engine.policy.dispatch:
row["scope"] = "自动派遣已关闭;" + row["scope"]
elif engine.policy.manual_eggs:
row["scope"] = "规则未启用:不自动清理"
for prefix, mapping in (("feed", "feed_targets"), ("gift", "gift_targets"), ("breakthrough", "breakthrough_targets")):
targets = config["policy"][mapping]
selected = key in targets
row[prefix + "_selected"], row[prefix + "_priority"] = selected, targets.get(key, 100)
row["edits"][prefix + "_selected"] = _edit(["policy", mapping, key], "target", default=100, unchecked="delete", disabled=mon.get("process") != 3)
row["edits"][prefix + "_priority"] = _edit(["policy", mapping, key], "integer", min=1, max=999, optional=True, disabled=not selected or mon.get("process") != 3)
row["edits"][prefix + "_selected"] = _edit(["policy", mapping, key], "target", default=100, unchecked="delete", disabled=bool(reason), reason=reason)
row["edits"][prefix + "_priority"] = _edit(["policy", mapping, key], "integer", min=1, max=999, optional=True, disabled=not selected or bool(reason), reason=reason)
dto["rows"].append(row)
dto["details"][key] = {"name": row["name"], "species": catalog.monster(mon["typeId"]).get("name", "未知"), "id": int(mon["id"]),
"level": row["level_text"], "quality": row["quality"], "reference_stats": catalog.reference_stats(mon),
"growth": {name: mon.get("g" + name.capitalize()) for name in ("atk", "def", "hp", "dex")},
"likes": row["likes"], "feel": row["feel_text"], "feed_exp": catalog.feed_exp(mon), "scope": row["scope"]}
"likes": row["likes"], "feel": row["feel_text"], "feed_exp": catalog.feed_exp(mon), "scope": row["scope"],
"培养角色": row["cultivation_role"], "主培养ID": row["primary_id"], "自动培养": reason or "同种唯一自动培养对象"}
if grouped:
known = {group["id"] for group in dto["groups"]}
for row in dto["rows"]:
if row["group"] not in known:
known.add(row["group"])
dto["groups"].append({"id": row["group"], "label": "培育室" if row["group"] == "incubator" else "未归属牧场", "count": counts[row["group"]], "collapsed": False})
dto["summary"] = f"{len(snapshot.raw['rooms'])} 座牧场;显示 {len(dto['rows'])} 只魔物"
dto["summary"] = (f"{len(snapshot.raw['rooms'])} 座牧场;显示 {len(dto['rows'])} 只魔物;"
"自动喂养 / 赠礼 / 突破仅限各类主培养;备选 / 重复项原勾选保留但不执行")
targets = [{"value": int(mon["id"]), "label": f"{catalog.monster_label(mon)} Lv.{mon.get('level', 1)}/{catalog.max_level(mon)}"}
for mon in snapshot.raw["monsters"] if mon.get("process") == 3 and catalog.max_level(mon) is not None and int(mon.get("level", 1)) < catalog.max_level(mon)]
dto["feed_targets"] = targets