Compare commits
6
Commits
4e2d39b612
...
13a462b6fc
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
13a462b6fc | ||
|
|
aeb67f3c9c | ||
|
|
e546f91e03 | ||
|
|
e22d7ba6fd | ||
|
|
514eae6745 | ||
|
|
6b1d21a2c5 |
@@ -35,6 +35,10 @@ __pycache__/
|
||||
# Written by 40250 uitaskbar.py at runtime.
|
||||
/mouse.cfg
|
||||
|
||||
# Written at runtime by the mt_* option windows (mt_pickup, mt_display, ...).
|
||||
/mt_*.cfg
|
||||
/Client/mt_*.cfg
|
||||
|
||||
# native Android client (./android/build.sh): SDL3 download, NDK builds, Gradle output
|
||||
/android/.gradle/
|
||||
/android/app/build/
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
# AVA2 换线适配进度(v1)
|
||||
|
||||
2026-10-15。只改了 metin2-client,服务端不需要改动。参考了 AVA2 的 `ENABLE_CHANNEL_CHANGE`(`Locale_inc.h`)。AVA2 客户端只接收 `HEADER_GC_CHANNEL`(121)来显示当前频道,真正的换线由服务端完成;AVA2 服务端源码不在本机,所以这里没有照搬它的做法。
|
||||
|
||||
## 与 AVA2 的差异
|
||||
|
||||
| 项目 | AVA2 | 本实现 |
|
||||
| --- | --- | --- |
|
||||
| 换线方式 | 服务端把角色传送到目标频道的核心 | 客户端依次走原有流程:`/logout` → 登录界面 → 用保存的账号登录目标频道 → 自动选择同一角色进入游戏 |
|
||||
| 服务端改动 | 需要(频道到端口的对应关系,或 DB/P2P 协议) | 不需要;本服务端的核心之间不知道其他频道的监听端口 |
|
||||
| 频道列表 | 服务端提供 | 客户端 `serverInfo.REGION_DICT`,与登录界面的频道列表相同 |
|
||||
| 等待时间 | 传送 | 原 `/logout` 倒计时(3 秒,战斗中 10 秒)加一次登录和读图 |
|
||||
|
||||
## 流程
|
||||
|
||||
1. 游戏内点“换线”,窗口列出当前服务器的频道。当前频道用 `【】` 标出且不能点。当前频道按 `MainStream` 的连接地址在 `serverInfo` 中查找;找不到时(例如测试端口 13040)显示“未知”,服务器取 `channel.inf` 中上次选择的服务器。
|
||||
2. 选择频道后发送原 `/logout`。服务端倒计时,结束后关闭连接;`OnRemoteDisconnect` 调用 `SetLoginPhase`。
|
||||
3. `introLogin.LoginWindow.Open` 之后,脚本把连接信息设为目标频道(认证服务器取 `REGION_AUTH_SERVER_DICT`),写入 `channel.inf` 和 `net.SetServerInfo`,打开 `stream.isAutoSelect` 并恢复原来的角色槽位,然后调用原 `LoginWindow.Connect`,账号密码取自 `MainStream.id/pwd`。
|
||||
4. `introSelect.SelectCharacterWindow.Open` 中原有的 `isAutoSelect` 分支选择同一槽位并 `StartGame`。
|
||||
5. 进入游戏后关闭 `isAutoSelect`,聊天框提示“已换到 CHx”。
|
||||
|
||||
换线进行中所有频道按钮都不能点:再次发送 `/logout` 会取消服务端倒计时。
|
||||
|
||||
## 失败处理
|
||||
|
||||
- 20 秒内服务端没有断开连接(例如刚战斗过,`IsHack` 拒绝退出),取消换线并提示。
|
||||
- 登录失败或连接失败时,取消换线、关闭 `isAutoSelect`,并显示原登录失败提示,之后可以手动登录。
|
||||
- 没有保存的账号密码时(例如自动登录信息不完整)不发送 `/logout`。
|
||||
|
||||
## 客户端
|
||||
|
||||
- 模块 `mt_channel`(`src/platform/ScriptLib/ChannelScript.inc`),在 `PythonBoot.cpp` 中安装:
|
||||
- 入口是小地图旁“显示”下方的“换线”按钮。
|
||||
- 挂接 `game.GameWindow.Open/Close/OnUpdate` 和 `introLogin.LoginWindow.Open/OnUpdate/OnLoginFailure/OnConnectFailure`。
|
||||
|
||||
## 证据
|
||||
|
||||
- `tests/wiki/test_channel.py`(CTest:`port.channel`)共 6 项通过,覆盖:
|
||||
- 当前频道定位(`serverInfo` 匹配、`channel.inf` 回退);
|
||||
- 完整换线:只发一次 `/logout`,登录窗口连接到目标频道和认证服务器,`isAutoSelect`、槽位、`channel.inf`、`SetServerInfo`,进入游戏后复位;
|
||||
- 退出超时、登录失败、同频道和无账号时拒绝;
|
||||
- 服务端 `do_cmd` 的 10 秒倒计时小于超时,且重复 `/logout` 会取消。
|
||||
- 2026-10-15 联机测试(203 正式频道,macOS 原生客户端,账号 admin,角色 `[SA]Admin`):
|
||||
- CH1(13000)→ CH2(13010)→ CH1,每次约 20 秒(倒计时 3 秒、登录约 2 秒、读图约 6 秒)。
|
||||
- 换线后角色在同一位置(64600, 79800),连接端口分别为 13010 和 13000,选人界面由原 `isAutoSelect` 自动进入。
|
||||
- 截图确认窗口布局、当前频道标记和换线中状态正常。
|
||||
|
||||
## 限制和未完成
|
||||
|
||||
- 换线经过登录界面,比服务端传送慢,期间会看到登录和读图画面。
|
||||
- 只支持 `serverInfo` 里有的频道;测试核心 channel5(13040)不在列表中,从它出发时当前频道显示“未知”。
|
||||
- 副本等地图没有做客户端限制:退出后重新登录由服务端按原规则决定角色位置。
|
||||
- macOS 桌面客户端没有中文字体,窗口文字显示为 `?`。
|
||||
- Android 真机测试未做。
|
||||
@@ -0,0 +1,56 @@
|
||||
# AVA2 显示开关适配进度(v1)
|
||||
|
||||
2026-10-15。只改了 metin2-client,服务端不需要改动。参考了 AVA2 的 `ENABLE_GRAPHIC_ON_OFF`(`InstanceBase.cpp` 中 `__CanRender` 的 effect_level 0–4)和 `HIDE_OBJECTS`(`background.SetVisiblePart`)。
|
||||
|
||||
## 与 AVA2 的差异
|
||||
|
||||
| 项目 | AVA2 | 本实现 |
|
||||
| --- | --- | --- |
|
||||
| 特效等级 | 0–4,在渲染判断里跳过 | 相同的 5 档;在 `CInstanceBase::Update` 中对角色挂载的特效调用 Active/Deactive,不改渲染路径 |
|
||||
| 摆摊、宠物、坐骑的显示范围 | 有 | 不移植:经典版没有离线摆摊和宠物 |
|
||||
| 树木、云 | `background.SetVisiblePart` | 相同,使用原有接口 |
|
||||
| 名字、伤害数字 | 原有选项 | 窗口内加了快捷开关,仍然写原来的 systemSetting,退出时由原配置保存 |
|
||||
|
||||
## 特效等级
|
||||
|
||||
| 等级 | 显示的特效 |
|
||||
| --- | --- |
|
||||
| 0 全部特效 | 全部 |
|
||||
| 1 只看怪物特效 | 自己、怪物、灵石 |
|
||||
| 2 只看玩家特效 | 自己、其他玩家 |
|
||||
| 3 只看自己特效 | 只有自己 |
|
||||
| 4 关闭全部特效 | 无,包括自己 |
|
||||
|
||||
## 客户端
|
||||
|
||||
- C++:
|
||||
- `CEffectManager::ActiveEffectInstance`。
|
||||
- `CActorInstance::SetAttachingEffectShown`:对已挂载的特效调用 Active/Deactive;关闭期间新挂载的特效也会立即 Deactive。使用 Deactive 而不是 Hide,避免和刺客隐身的 Show/Hide 冲突。
|
||||
- `CPythonSystem::Get/SetEffectLevel`,越界值按 0 处理;不写入 metin2.cfg。
|
||||
- `systemSetting.SetEffectLevel/GetEffectLevel`。
|
||||
- `CInstanceBase::__UpdateEffectShown`,每帧在 `Update` 开头按上表判断。
|
||||
- `CMapOutdoor::RenderPCBlocker`:离镜头近、挡住角色的树会作为遮挡物(PC blocker)单独绘制,不经过 `RenderTree`,所以原来关闭树木后这类树仍然显示。现在隐藏树木时跳过遮挡物中的树。AVA2 有同样的问题。
|
||||
- 模块 `mt_display`(`src/platform/ScriptLib/DisplayScript.inc`),在 `PythonBoot.cpp` 中安装:
|
||||
- 入口是小地图旁“拾取”下方的“显示”按钮。
|
||||
- 窗口“显示设置”包含 5 个特效等级、显示树木、显示云、总是显示名字、显示伤害数字,`【】` 表示当前选中。
|
||||
- 设置保存在客户端目录的 `mt_display.cfg`,格式为“特效等级 树木 云”,默认 `0 1 1`,损坏时回到默认值。
|
||||
- 特效等级在启动时生效;树木和云在进入游戏(`GameWindow.Open`)时生效。
|
||||
|
||||
## 证据
|
||||
|
||||
- `tests/wiki/test_display.py`(CTest:`port.display`)共 3 项通过,覆盖:
|
||||
- 默认值、配置文件读写、损坏的配置;
|
||||
- 进入游戏时生效,窗口按钮、配置保存、名字和伤害开关;
|
||||
- 5 档和 C++ 规则一致。
|
||||
- `test_pickup.py`(7 项)和 `test_switchbot.py`(6 项)仍然通过。
|
||||
- 2026-10-15 联机测试(203 测试核心 channel5,macOS 原生客户端,账号 admin):
|
||||
- 切到等级 4 并关闭树木后,配置为 `4 0 1`;恢复后为 `0 1 1`。
|
||||
- 截图确认窗口布局正常。
|
||||
- 用 `/goto 646 798` 走到离树约 7 米的位置截图对比:等级 4 时 GM 标志和武器光效消失;关闭树木后树消失(修复遮挡物问题之前,这棵树仍然显示);恢复后都回来。
|
||||
|
||||
## 限制和未完成
|
||||
|
||||
- 只控制挂载在角色上的特效(装备光效、buff、种族特效)。单独播放的特效和飞行特效(技能弹道、命中特效)不受影响。
|
||||
- macOS 桌面客户端没有中文字体,窗口文字显示为 `?`(原版界面同样乱码);Android 使用 CFF FreeType,不受影响。
|
||||
- 树的影子烘焙在地形阴影图里,关闭树木后地面上仍有树影(与 AVA2 相同)。
|
||||
- Android 真机测试未做。
|
||||
@@ -116,3 +116,11 @@
|
||||
2026-10-15 后续批次:阶段 0 的只读能力协商、阶段 2/3 的掉落/来源/宝箱查询、阶段 4 属性面板已实现并在隔离环境测试;未部署 203,待联机与真机验收。范围和缺口见 AVA2-READONLY-FEATURES.md。
|
||||
|
||||
2026-10-15 再续:龙穴/周任务信息与提醒、共享真实掉落开关的活动日历已实现并在隔离环境验证。副本仅首批龙穴;活动仅月光宝箱/圣诞袜,生产未部署,无生产排期。自动洗练/锁定、战令、模型预览、批量开箱仍待实现。见 AVA2-DUNGEON-CALENDAR.md。
|
||||
|
||||
2026-10-15 自动洗练 v1(阶段 6,不含属性锁定):服务端 mt_switchbot 逐次调用原 UseItem 洗练路径,客户端 mt_switchbot 窗口;隔离环境编译与桩测试通过,macOS 客户端已在 203 测试核心联机验收;未部署 203 正式环境、未做 Android 真机测试。属性锁定仍待存储设计。见 AVA2-SWITCHBOT.md。
|
||||
|
||||
2026-10-15 批量拾取(计划外追加,参考 AVA2 do_pickup_all):服务端 mt_pickup 对范围内自己的物品按分类逐件调用原 PickupItem,客户端在拾取键(Z)上接入并提供分类设置窗口;macOS 客户端已在 203 测试核心联机验收,未部署 203 正式环境、未做 Android 真机测试和触屏按钮。见 AVA2-PICKUP.md。
|
||||
|
||||
2026-10-15 显示开关(计划外追加,参考 AVA2 ENABLE_GRAPHIC_ON_OFF / HIDE_OBJECTS):仅客户端,5 档特效等级(挂载特效 Active/Deactive)、树木和云开关、名字和伤害数字快捷开关;macOS 客户端已在 203 测试核心联机验收,未做 Android 真机测试。不移植摆摊/宠物/坐骑显示范围。见 AVA2-DISPLAY.md。
|
||||
|
||||
2026-10-15 换线(计划外追加,参考 AVA2 ENABLE_CHANNEL_CHANGE):仅客户端,按原流程 /logout → 登录目标频道(serverInfo 频道表 + 保存的账号)→ isAutoSelect 进入同一角色,不做服务端传送;macOS 客户端已在 203 正式频道 CH1↔CH2 联机验收,未做 Android 真机测试。见 AVA2-CHANNEL.md。
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
# AVA2 批量拾取适配进度(v1)
|
||||
|
||||
2026-10-15。修改了 metin2-client 和 metin2-server,AVA2 代码只作参考(`do_pickup_all`、`ENABLE_AUTOMATIC_PICK_UP_SYSTEM`)。服务端规则和协议见 `metin2-server/docs/FEATURE-PICKUP.md`。
|
||||
|
||||
## 与 AVA2 的差异
|
||||
|
||||
| 项目 | AVA2 | 本实现 |
|
||||
| --- | --- | --- |
|
||||
| 触发 | 新包头 `HEADER_CG_ITEMS_PICKUP`,以及付费状态 70002(AFFECT_AUTO_PICK_UP)下的自动拾取 | 聊天命令 `/mt_pickup`,不新增包头;只在按拾取键时触发,不做自动拾取和付费状态 |
|
||||
| 范围 | 自己的物品 | 相同:只拾取自己的或无主的物品;队伍分配的物品不批量拾取 |
|
||||
| 拾取过程 | 自己实现 | 每件物品都调用原 `PickupItem`,距离、堆叠、背包空间、GET 日志、任务触发都不变 |
|
||||
| 分类 | CheckItemCanGet 模式掩码 | 8 个分类位:金币、武器、防具/首饰、技能书、灵石、材料、时装、其他 |
|
||||
|
||||
## 客户端
|
||||
|
||||
- 模块 `mt_pickup`(`src/platform/ScriptLib/PickupScript.inc`),在 `PythonBoot.cpp` 中安装。替换了 `GameWindow.PickUpItem`(Z 键和 ` 键)。
|
||||
- 开启时,按拾取键会发送 `/mt_pickup 1 掩码`。等待回复时,以及两次发送间隔不足 0.5 秒时,按键会被吞掉(防止按住 Z 连发)。关闭时走原来的单个拾取。
|
||||
- 3 秒没有回复:在聊天框提示一次“服务器尚未启用批量拾取”,之后改用单个拾取;再收到回复会自动恢复。
|
||||
- 设置窗口:入口是小地图旁“洗练”下方的“拾取”按钮。窗口内可开关批量拾取、选择 8 个分类(`【】` 表示已选,至少保留一个),并显示上次结果(附近 N 件、拾取 N 件、失败 N 件)。设置保存在客户端目录的 `mt_pickup.cfg`,格式为“开关 掩码”。
|
||||
- 单件物品的提示仍由服务端发送;失败提示(例如背包已满)只发一次。
|
||||
|
||||
## 证据
|
||||
|
||||
- `tests/wiki/test_pickup.py`(CTest:`port.pickup`)共 7 项通过,覆盖:
|
||||
- 发送节流和等待回复;
|
||||
- done/error 解析,畸形行和其他前缀;
|
||||
- 超时后改用单个拾取,迟到的回复会恢复批量拾取;
|
||||
- 关闭开关、分类掩码、至少保留一个分类;
|
||||
- 配置文件读写和损坏的配置;
|
||||
- GameWindow 钩子:入口位置、拾取键、命令拦截、窗口开关;
|
||||
- 和服务端的分类位、错误码、0.5 秒间隔一致。
|
||||
- `tests/wiki/test_switchbot.py` 仍然通过。
|
||||
- 2026-10-15 联机测试(203 测试核心 channel5/first,端口 13040,使用隔离编译的 game;macOS 原生客户端,账号 admin)。先用 `/item` 生成并逐件丢下武器 19、铠甲 11209、材料 30003、灵石 28030、技能书 50300 和 1000 金币:
|
||||
- 掩码 2(武器):`done 1 1 0`,只拾回武器。
|
||||
- 掩码 48(灵石+材料):`done 2 2 0`。
|
||||
- 掩码 255:`done 3 3 0`,拾回铠甲、技能书和金币(金币数恢复)。
|
||||
- 地上已没有物品:`done 0 0 0`;紧接着再发一次:`error rate`。
|
||||
- log.log 有 5 行 GET,每件物品一行,和 DROP 一一对应。原路径拾取金币不写 GET 日志。
|
||||
- 测试核心 syserr 没有新错误。丢金币时出现的 LOCALE_ERROR 来自原有的丢金币提示。
|
||||
|
||||
## 未完成
|
||||
|
||||
- Android 真机测试和触屏拾取按钮(`touch_controller.h` 的按钮发送 DIK 键码,需要再加布局)。
|
||||
- 背包已满时的联机测试(服务端桩测试已覆盖)。
|
||||
- 服务端还没有部署到 203 正式环境。
|
||||
- 自动狩猎自带的客户端拾取(`PICKUP_TEXTS`)没有改动。
|
||||
@@ -0,0 +1,57 @@
|
||||
# AVA2 自动洗练适配进度(v1,不含属性锁定)
|
||||
|
||||
2026-10-15。修改了 metin2-client 和 metin2-server,AVA2 代码只作参考。服务端规则和协议见 `metin2-server/docs/FEATURE-SWITCHBOT.md`。
|
||||
|
||||
## 与 AVA2 的差异
|
||||
|
||||
| 项目 | AVA2 | 本实现 |
|
||||
| --- | --- | --- |
|
||||
| 窗口 | 新增 SWITCHBOT 物品窗口,5 个物品槽加 1 个道具槽 | 不新增窗口类型,物品留在背包,按物品 ID 绑定;每个角色同一时间只洗 1 件 |
|
||||
| 洗练执行 | 自己实现消耗和 ChangeAttribute,绕过手动检查和 ItemLog | 每次都调用原 `UseItem`,检查、概率、日志、扣道具都和手动洗练一样;71151/76023 仍只能洗等级上限 ≤40 的武器和衣服 |
|
||||
| 速度 | 0.1 秒一次 | 0.25 秒一次(约 4 次/秒) |
|
||||
| 物品被移动 | 拦截移动、交易、出售等路径 | 每次洗练前重新检查:物品不在背包、已装备、易主时停止(item_gone);交易、商店、仓库、合成界面打开时停止(busy) |
|
||||
| 换线 / 下线 | 通过 P2P 转移,继续洗 | 直接停止,不离线洗练 |
|
||||
|
||||
匹配规则和 AVA2 相同:最多 2 套方案,每套 1–5 条“属性 ≥ 阈值”;任意一套全部达标就停止,只看前 5 条普通属性。
|
||||
|
||||
## 客户端
|
||||
|
||||
- 模块 `mt_switchbot`(`src/platform/ScriptLib/SwitchbotScript.inc`),在 `PythonBoot.cpp` 中安装。入口是小地图旁“百科”按钮下方的“洗练”按钮。
|
||||
- 物品:扫描背包里至少有一条属性的武器和防具,用 `<` `>` 切换。洗练道具:扫描子类型为 USE_CHANGE_ATTRIBUTE 的道具,显示数量。次数上限可选 10、50、100、200、500、1000。
|
||||
- 可选属性和最大值由服务端 `attrs` 下发,客户端不自己推算。添加属性时分页点选;阈值用 -/+ 调整,步长为最大值的 1/5,默认取最大值。
|
||||
- 运行时锁定所有设置,实时显示次数、剩余道具、停止原因和当前 5 条属性。停止时在聊天框提示;达标时如果窗口已关闭,会自动打开。
|
||||
- 命令间隔至少 0.3 秒,同一时间只有一个请求在等待回复。4 秒没有回复就显示“服务器尚未启用自动洗练”。`attrs` 只接受完整、连续的回复,不完整的整批丢弃。
|
||||
- 文字都用 GBK 可编码的字符(不用 ◀/▶/⚠)。
|
||||
|
||||
## 证据
|
||||
|
||||
- `tests/wiki/test_switchbot.py`(CTest:`port.switchbot`)共 6 项通过,覆盖:
|
||||
- 请求节流和合并;
|
||||
- 不完整的 attrs 回复被拒绝;
|
||||
- start 命令的拼装和校验;
|
||||
- state/error 解析和超时;
|
||||
- 和服务端的原因码、错误码、上限一致;
|
||||
- 窗口流程:扫描 → 读取属性 → 选属性 → 开始 → 达标提示。
|
||||
- 脚本能在 Python 2.7 下编译。`tests/wiki/test_service.py` 仍然通过。
|
||||
- 2026-10-15 联机测试(203 额外开的测试核心 channel5/first,端口 13040,使用隔离编译的 game;macOS 原生客户端,账号 admin,物品为背包 33 格的剑 279,道具 71084):
|
||||
- 上限 10 次:洗满 10 次后停止(limit),约 4 次/秒。
|
||||
- 两套方案、阈值 1:第 18 次达标(matched)。
|
||||
- 已经达标的物品:0 次就停止,不扣道具。
|
||||
- 洗练中把物品从 33 格移到 90 格:继续洗,窗口跟到 90 格;点停止后显示 stopped。
|
||||
- 洗练中退出客户端:服务端立即停止。
|
||||
- log.log 中 CHANGE_ATTRIBUTE 共 72 行,和总次数一致。
|
||||
- busy:洗练中摆摊(先给 50200 摊位包袱;没有它 `OpenMyShop` 会提前返回、摊位不会开,第一次测试就是这样误判的),摊位开出约 1 秒后停止(busy),共洗 6 次。
|
||||
- no_scroll:用 76014(共 6 张)、上限 10,洗 6 次后停止(no_scroll),道具剩 0。
|
||||
- rejected:对 90 级剑用 71151(原路径只允许等级 <= 40):0 次就停止(rejected),道具未扣。
|
||||
- 截图里窗口布局正常。仓库自带的 `Client` 是英文 cp1252 locale,所以中文显示为 `????`;需要 zh locale 客户端才能看到中文。
|
||||
- 联机测试发现并修复了两个窗口问题,`test_switchbot.py` 已加回归用例:
|
||||
- 洗练中移动物品后,选中项会跳到别的物品:现在按服务端报告的格子跟随。
|
||||
- 空闲时移动物品后选中项丢失:现在退而按相同 vnum 匹配。
|
||||
- 服务端 `tests/features/test_switchbot.py` 和 `test_queries.py` 通过。203 的隔离目录 `/root/metin2-features-dev` 完整编译通过。
|
||||
|
||||
## 未完成
|
||||
|
||||
- Android 真机测试。
|
||||
- macOS 构建需要 `-DMT_40250_SOURCE=<含 EterPack/EterPack.cpp 的源码目录>` 来生成 pack 密钥,否则 system.py 读不出来(RunMain Error)。本机没有 40250 源码,这次用的是 AVA2 的 `TEST/3. Source BIN/Client`,两者密钥相同。
|
||||
- 服务端还没有部署到 203 正式环境。
|
||||
- 属性锁定(阶段 6 后半):需要单独的存储设计。
|
||||
@@ -0,0 +1,240 @@
|
||||
// PORT: AVA2-style channel switch (ENABLE_CHANNEL_CHANGE), client-only. Instead of a server-side warp it runs
|
||||
// the original paths in order: /logout (the server's 3 s / 10 s countdown, which also refuses while fighting),
|
||||
// the disconnect brings back introLogin.LoginWindow, which then connects to the chosen channel of serverInfo
|
||||
// with the account kept by networkModule.MainStream, and stream.isAutoSelect makes introSelect start the same
|
||||
// character. See docs/AVA2-CHANNEL.md.
|
||||
static const char c_szChannelScript[] = R"PY(# -*- coding: utf-8 -*-
|
||||
import app
|
||||
import chat
|
||||
import game
|
||||
import grp
|
||||
import introLogin
|
||||
import net
|
||||
import ui
|
||||
import weakref
|
||||
from mt_biolog import Action, Text, L
|
||||
from mt_wiki import B
|
||||
|
||||
try:
|
||||
import serverInfo
|
||||
except ImportError:
|
||||
serverInfo=None
|
||||
|
||||
g_window=None
|
||||
g_entry=None
|
||||
CHANNEL_FILE='channel.inf' # the file introLogin's server board reads
|
||||
LOGOUT_TIMEOUT=20. # countdown is 3 s, 10 s while fighting; nothing back means the server refused
|
||||
LOGIN_TIMEOUT=30.
|
||||
|
||||
|
||||
def Locate(addr,port):
|
||||
# (region, server, channel) of serverInfo whose game address is addr:port; channel 0 when none matches.
|
||||
regions=getattr(serverInfo,'REGION_DICT',{})
|
||||
for region in sorted(regions):
|
||||
for server in sorted(regions[region]):
|
||||
for channel,data in sorted(regions[region][server].get('channel',{}).items()):
|
||||
if data.get('ip')==addr and data.get('tcp_port')==port:return region,server,channel
|
||||
try:
|
||||
f=open(CHANNEL_FILE,'r');words=f.read().split();f.close()
|
||||
server=int(words[0]);region=int(words[2]) if len(words)>2 else 0
|
||||
if server in regions.get(region,{}):return region,server,0
|
||||
except (IOError,OSError,ValueError,IndexError):pass
|
||||
for region in sorted(regions):
|
||||
for server in sorted(regions[region]):return region,server,0
|
||||
return None
|
||||
|
||||
|
||||
def Channels(place):
|
||||
if not place:return []
|
||||
region,server,current=place
|
||||
data=serverInfo.REGION_DICT[region][server]
|
||||
return [(channel,info) for channel,info in sorted(data.get('channel',{}).items())]
|
||||
|
||||
|
||||
class Switcher(object):
|
||||
# stage: None, 'logout' (waiting for the server to close the session), 'login' (connecting to the target).
|
||||
def __init__(self,send,now,listener=None):
|
||||
self.send=send;self.now=now;self.listener=listener
|
||||
self.stage=None;self.deadline=0;self.target=None;self.account=None;self.error=None;self.stream=None
|
||||
|
||||
def Busy(self):return self.stage is not None
|
||||
|
||||
def Start(self,stream,place,channel):
|
||||
if self.Busy():return False
|
||||
region,server,current=place
|
||||
info=serverInfo.REGION_DICT[region][server]['channel'].get(channel)
|
||||
if not info or channel==current:self.error='channel';self.Notify('error');return False
|
||||
if not getattr(stream,'id','') or not getattr(stream,'pwd',''):self.error='account';self.Notify('error');return False
|
||||
auth=getattr(serverInfo,'REGION_AUTH_SERVER_DICT',{}).get(region,{}).get(server)
|
||||
account=(auth['ip'],auth['port']) if auth else (stream.account_addr,stream.account_port)
|
||||
self.target=dict(region=region,server=server,channel=channel,ip=info['ip'],port=info['tcp_port'],
|
||||
account=account,label='%s, %s'%(serverInfo.REGION_DICT[region][server].get('name',''),info.get('name','')))
|
||||
self.account=(stream.id,stream.pwd,stream.GetCharacterSlot());self.stream=stream
|
||||
self.error=None;self.stage='logout';self.deadline=self.now()+LOGOUT_TIMEOUT
|
||||
self.send('/logout');self.Notify('start')
|
||||
return True
|
||||
|
||||
def Tick(self):
|
||||
if self.stage and self.now()>=self.deadline:
|
||||
self.error='timeout' if self.stage=='logout' else 'login';self.Clear();self.Notify('error')
|
||||
|
||||
def Clear(self):
|
||||
if self.stream:self.stream.isAutoSelect=0 # never leave the original auto-select on for a manual login
|
||||
self.stage=None;self.target=None;self.account=None;self.stream=None
|
||||
|
||||
def Notify(self,kind):
|
||||
if self.listener:self.listener(kind)
|
||||
|
||||
def OnLoginWindow(self,window):
|
||||
# LoginWindow.Open has just reset the connect info from loginInfo.xml; point it at the target channel.
|
||||
if self.stage!='logout':return False
|
||||
t=self.target;user,pwd,slot=self.account;stream=window.stream
|
||||
stream.SetConnectInfo(t['ip'],t['port'],t['account'][0],t['account'][1])
|
||||
stream.SetCharacterSlot(slot);stream.isAutoSelect=1
|
||||
net.SetServerInfo(t['label'].strip())
|
||||
try:
|
||||
f=open(CHANNEL_FILE,'w');f.write('%d %d %d'%(t['server'],t['channel'],t['region']));f.close()
|
||||
except (IOError,OSError):pass
|
||||
self.stage='login';self.deadline=self.now()+LOGIN_TIMEOUT
|
||||
window.Connect(user,pwd)
|
||||
return True
|
||||
|
||||
def OnLoginFailure(self,error):
|
||||
if self.stage=='login':self.error='login';self.Clear();self.Notify('error')
|
||||
|
||||
def OnGame(self,stream):
|
||||
if self.stage=='login':
|
||||
channel=self.target['channel'];self.Clear();self.Notify('done')
|
||||
return channel
|
||||
return 0
|
||||
|
||||
|
||||
ERRORS={'channel':'无法换到该频道','account':'没有保存的登录信息,请重新登录后再换线',
|
||||
'timeout':'服务器没有退出(战斗中或不允许退出),换线已取消','login':'登录目标频道失败'}
|
||||
|
||||
|
||||
class ChannelWindow(ui.Window):
|
||||
def __init__(self,switcher,stream):
|
||||
ui.Window.__init__(self);self.SetWindowName('ChannelWindow');self.AddFlag('float');self.AddFlag('movable')
|
||||
self.switcher=switcher;self.stream=stream;self.place=None;self.channelButtons=[]
|
||||
self.SetSize(332,260)
|
||||
self.heading=Text(self,18,18,'换线',0xffffd68b)
|
||||
self.closeButton=Action(self,256,6,60,'关闭',self.Hide)
|
||||
self.current=Text(self,18,52,'',0xffc3b7a1)
|
||||
self.status=Text(self,18,232,'',0xffc3b7a1)
|
||||
self.Hide()
|
||||
|
||||
def Buttons(self):return [self.closeButton]+self.channelButtons
|
||||
|
||||
def Build(self):
|
||||
for b in self.channelButtons:b.Hide();b.event=None
|
||||
self.place=Locate(self.stream.addr,self.stream.port)
|
||||
channels=Channels(self.place)
|
||||
self.channelButtons=[Action(self,18+(i%2)*152,82+(i//2)*52,144,'',lambda channel=channel:self.Switch(channel))
|
||||
for i,(channel,info) in enumerate(channels)]
|
||||
self.SetSize(332,max(160,82+(len(channels)+1)//2*52+40));self.status.SetPosition(18,self.GetHeight()-28)
|
||||
|
||||
def Open(self):self.Build();self.Refresh();self.SetCenterPosition();self.Show();self.SetTop()
|
||||
|
||||
def Switch(self,channel):
|
||||
if self.place:self.switcher.Start(self.stream,self.place,channel)
|
||||
self.Refresh()
|
||||
|
||||
def Refresh(self):
|
||||
current=self.place[2] if self.place else 0
|
||||
channels=Channels(self.place);busy=self.switcher.Busy()
|
||||
name=dict(channels).get(current,{}).get('name')
|
||||
self.current.SetText(L('当前频道:'+(name if name else '未知')))
|
||||
for button,(channel,info) in zip(self.channelButtons,channels):
|
||||
button.SetText(L(B(u'【%s】'%info.get('name','') if channel==current else info.get('name',''))))
|
||||
button.SetEnabled(not busy and channel!=current)
|
||||
self.status.SetText(L(self.StatusText()))
|
||||
|
||||
def StatusText(self):
|
||||
s=self.switcher
|
||||
if s.stage=='logout':return '正在退出,稍后自动登录 %s'%s.target['label'].split(', ')[-1]
|
||||
if s.stage=='login':return '正在登录 %s'%s.target['label'].split(', ')[-1]
|
||||
if s.error:return '!'+ERRORS[s.error]
|
||||
if not self.place:return '!没有可用的频道列表'
|
||||
return '退出后自动登录所选频道,并进入同一角色'
|
||||
|
||||
def OnRender(self):
|
||||
x,y=self.GetGlobalPosition();grp.SetColor(0xf51b1916);grp.RenderBar(x,y,self.GetWidth(),self.GetHeight());grp.SetColor(0xff9b7b48);grp.RenderBox(x,y,self.GetWidth(),self.GetHeight())
|
||||
|
||||
def OnPressEscapeKey(self):self.Hide();return True
|
||||
|
||||
def Destroy(self):
|
||||
self.Hide()
|
||||
for b in self.Buttons():b.event=None
|
||||
|
||||
|
||||
class Entry(Action):
|
||||
def __init__(self,window):
|
||||
Action.__init__(self,None,0,0,64,'换线',Toggle)
|
||||
self.minimap=weakref.proxy(window.interface.wndMiniMap);self.SetWindowName('ChannelEntry');self.OnUpdate()
|
||||
|
||||
def OnUpdate(self):
|
||||
x,y=self.minimap.GetGlobalPosition();self.SetPosition(max(4,x-68),y+304)
|
||||
|
||||
|
||||
def OnSwitch(kind):
|
||||
if kind=='error':chat.AppendChat(chat.CHAT_TYPE_INFO,L(ERRORS[g_switcher.error]))
|
||||
if g_window:g_window.Refresh()
|
||||
|
||||
|
||||
g_switcher=Switcher(net.SendChatPacket,app.GetTime,OnSwitch)
|
||||
|
||||
|
||||
def Toggle():
|
||||
if g_window:
|
||||
if g_window.IsShow():g_window.Hide()
|
||||
else:g_window.Open()
|
||||
|
||||
|
||||
_open=game.GameWindow.Open
|
||||
_close=game.GameWindow.Close
|
||||
_update=game.GameWindow.OnUpdate
|
||||
_login_open=introLogin.LoginWindow.Open
|
||||
_login_update=introLogin.LoginWindow.OnUpdate
|
||||
_login_failure=introLogin.LoginWindow.OnLoginFailure
|
||||
_connect_failure=introLogin.LoginWindow.OnConnectFailure
|
||||
|
||||
def Open(self):
|
||||
global g_window,g_entry
|
||||
_open(self)
|
||||
channel=g_switcher.OnGame(self.stream)
|
||||
g_window=ChannelWindow(g_switcher,self.stream);g_entry=Entry(self)
|
||||
if channel:
|
||||
name=dict(Channels(Locate(self.stream.addr,self.stream.port))).get(channel,{}).get('name','')
|
||||
chat.AppendChat(chat.CHAT_TYPE_INFO,L('已换到 %s'%name))
|
||||
|
||||
def Close(self):
|
||||
global g_window,g_entry
|
||||
if g_entry:g_entry.Hide();g_entry.event=None;g_entry=None
|
||||
if g_window:g_window.Destroy();g_window=None
|
||||
_close(self)
|
||||
|
||||
def OnUpdate(self):
|
||||
_update(self)
|
||||
if g_switcher.stage=='logout':g_switcher.Tick()
|
||||
|
||||
def LoginOpen(self):
|
||||
_login_open(self);g_switcher.OnLoginWindow(self)
|
||||
|
||||
def LoginUpdate(self):
|
||||
_login_update(self);g_switcher.Tick()
|
||||
|
||||
def LoginFailure(self,error):
|
||||
g_switcher.OnLoginFailure(error);_login_failure(self,error)
|
||||
|
||||
def ConnectFailure(self):
|
||||
g_switcher.OnLoginFailure('connect');_connect_failure(self)
|
||||
|
||||
game.GameWindow.Open=Open
|
||||
game.GameWindow.Close=Close
|
||||
game.GameWindow.OnUpdate=OnUpdate
|
||||
introLogin.LoginWindow.Open=LoginOpen
|
||||
introLogin.LoginWindow.OnUpdate=LoginUpdate
|
||||
introLogin.LoginWindow.OnLoginFailure=LoginFailure
|
||||
introLogin.LoginWindow.OnConnectFailure=ConnectFailure
|
||||
)PY";
|
||||
@@ -0,0 +1,141 @@
|
||||
// PORT: AVA2-style display options (ENABLE_GRAPHIC_ON_OFF effect level, HIDE_OBJECTS tree/cloud parts),
|
||||
// client-only. The effect level is systemSetting.SetEffectLevel (CInstanceBase::__UpdateEffectShown deactivates
|
||||
// attached effects); trees and clouds use the original background.SetVisiblePart; names and damage numbers
|
||||
// are shortcuts to the original game options. See docs/AVA2-DISPLAY.md.
|
||||
static const char c_szDisplayScript[] = R"PY(# -*- coding: utf-8 -*-
|
||||
import background
|
||||
import game
|
||||
import grp
|
||||
import systemSetting
|
||||
import ui
|
||||
import weakref
|
||||
from mt_biolog import Action, Text, L
|
||||
from mt_wiki import B
|
||||
|
||||
g_window=None
|
||||
g_entry=None
|
||||
CONFIG='mt_display.cfg'
|
||||
LEVELS=(u'全部特效',u'只看怪物特效',u'只看玩家特效',u'只看自己特效',u'关闭全部特效')
|
||||
LEVEL_HINTS=('显示所有角色的特效','隐藏其他玩家和NPC的特效,保留自己和怪物的','隐藏怪物和NPC的特效,保留玩家的',
|
||||
'只保留自己的特效','连自己的特效也隐藏')
|
||||
|
||||
|
||||
class Options(object):
|
||||
def __init__(self):self.effect=0;self.tree=True;self.cloud=True
|
||||
|
||||
def Load(self,text):
|
||||
words=text.split()
|
||||
if len(words)!=3 or not all(w.isdigit() and len(w)==1 for w in words):return
|
||||
effect,tree,cloud=[int(w) for w in words]
|
||||
if effect<len(LEVELS) and tree in (0,1) and cloud in (0,1):self.effect=effect;self.tree=tree==1;self.cloud=cloud==1
|
||||
|
||||
def Dump(self):return '%d %d %d'%(self.effect,int(self.tree),int(self.cloud))
|
||||
|
||||
def Apply(self):
|
||||
systemSetting.SetEffectLevel(self.effect)
|
||||
background.SetVisiblePart(background.PART_TREE,int(self.tree))
|
||||
background.SetVisiblePart(background.PART_CLOUD,int(self.cloud))
|
||||
|
||||
|
||||
def LoadConfig(options):
|
||||
try:
|
||||
f=open(CONFIG,'r');text=f.read();f.close();options.Load(text)
|
||||
except (IOError,OSError):pass
|
||||
|
||||
|
||||
def SaveConfig(options):
|
||||
try:
|
||||
f=open(CONFIG,'w');f.write(options.Dump());f.close()
|
||||
except (IOError,OSError):pass
|
||||
|
||||
|
||||
def Mark(text,on):return L(B(u'【%s】'%text if on else text))
|
||||
|
||||
|
||||
class DisplayWindow(ui.Window):
|
||||
def __init__(self,options):
|
||||
ui.Window.__init__(self);self.SetWindowName('DisplayWindow');self.AddFlag('float');self.AddFlag('movable')
|
||||
self.options=options;self.SetSize(332,404)
|
||||
self.heading=Text(self,18,18,'显示设置',0xffffd68b)
|
||||
self.closeButton=Action(self,256,6,60,'关闭',self.Hide)
|
||||
self.effectText=Text(self,18,54,'特效',0xffc3b7a1)
|
||||
self.levelButtons=[Action(self,18+(i%2)*152,76+(i//2)*52,144,'',lambda level=i:self.SetLevel(level)) for i in range(len(LEVELS))]
|
||||
self.sceneText=Text(self,18,238,'场景和文字',0xffc3b7a1)
|
||||
self.treeButton=Action(self,18,260,144,'',self.ToggleTree)
|
||||
self.cloudButton=Action(self,170,260,144,'',self.ToggleCloud)
|
||||
self.nameButton=Action(self,18,312,144,'',self.ToggleName)
|
||||
self.damageButton=Action(self,170,312,144,'',self.ToggleDamage)
|
||||
self.status=Text(self,18,376,'',0xffc3b7a1)
|
||||
self.Refresh();self.Hide()
|
||||
|
||||
def Buttons(self):return [self.closeButton,self.treeButton,self.cloudButton,self.nameButton,self.damageButton]+self.levelButtons
|
||||
|
||||
def Open(self):self.Refresh();self.SetCenterPosition();self.Show();self.SetTop()
|
||||
|
||||
def Changed(self):self.options.Apply();SaveConfig(self.options);self.Refresh()
|
||||
|
||||
def SetLevel(self,level):self.options.effect=level;self.Changed()
|
||||
|
||||
def ToggleTree(self):self.options.tree=not self.options.tree;self.Changed()
|
||||
|
||||
def ToggleCloud(self):self.options.cloud=not self.options.cloud;self.Changed()
|
||||
|
||||
# Names and damage numbers are the original game options (saved by the client config on exit).
|
||||
def ToggleName(self):systemSetting.SetAlwaysShowNameFlag(not systemSetting.IsAlwaysShowName());self.Refresh()
|
||||
|
||||
def ToggleDamage(self):systemSetting.SetShowDamageFlag(not systemSetting.IsShowDamage());self.Refresh()
|
||||
|
||||
def Refresh(self):
|
||||
o=self.options
|
||||
for i,button in enumerate(self.levelButtons):button.SetText(Mark(LEVELS[i],i==o.effect))
|
||||
self.treeButton.SetText(Mark(u'显示树木',o.tree));self.cloudButton.SetText(Mark(u'显示云',o.cloud))
|
||||
self.nameButton.SetText(Mark(u'总是显示名字',systemSetting.IsAlwaysShowName()))
|
||||
self.damageButton.SetText(Mark(u'显示伤害数字',systemSetting.IsShowDamage()))
|
||||
self.status.SetText(L(LEVEL_HINTS[o.effect]))
|
||||
|
||||
def OnRender(self):
|
||||
x,y=self.GetGlobalPosition();grp.SetColor(0xf51b1916);grp.RenderBar(x,y,self.GetWidth(),self.GetHeight());grp.SetColor(0xff9b7b48);grp.RenderBox(x,y,self.GetWidth(),self.GetHeight())
|
||||
|
||||
def OnPressEscapeKey(self):self.Hide();return True
|
||||
|
||||
def Destroy(self):
|
||||
self.Hide()
|
||||
for b in self.Buttons():b.event=None
|
||||
|
||||
|
||||
class Entry(Action):
|
||||
def __init__(self,window):
|
||||
Action.__init__(self,None,0,0,64,'显示',Toggle)
|
||||
self.minimap=weakref.proxy(window.interface.wndMiniMap);self.SetWindowName('DisplayEntry');self.OnUpdate()
|
||||
|
||||
def OnUpdate(self):
|
||||
x,y=self.minimap.GetGlobalPosition();self.SetPosition(max(4,x-68),y+252)
|
||||
|
||||
|
||||
g_options=Options()
|
||||
LoadConfig(g_options)
|
||||
systemSetting.SetEffectLevel(g_options.effect)
|
||||
|
||||
|
||||
def Toggle():
|
||||
if g_window:
|
||||
if g_window.IsShow():g_window.Hide()
|
||||
else:g_window.Open()
|
||||
|
||||
|
||||
_open=game.GameWindow.Open
|
||||
_close=game.GameWindow.Close
|
||||
|
||||
def Open(self):
|
||||
global g_window,g_entry
|
||||
_open(self);g_options.Apply();g_window=DisplayWindow(g_options);g_entry=Entry(self)
|
||||
|
||||
def Close(self):
|
||||
global g_window,g_entry
|
||||
if g_entry:g_entry.Hide();g_entry.event=None;g_entry=None
|
||||
if g_window:g_window.Destroy();g_window=None
|
||||
_close(self)
|
||||
|
||||
game.GameWindow.Open=Open
|
||||
game.GameWindow.Close=Close
|
||||
)PY";
|
||||
@@ -0,0 +1,194 @@
|
||||
// PORT: AVA2-style batch pickup (do_pickup_all), driven by the server's /mt_pickup command. With batch
|
||||
// pickup on, the pickup key (GameWindow.PickUpItem, Z / `) asks the server to pick up every own item in
|
||||
// range of the chosen categories; each item still goes through the original pickup path. Against a server
|
||||
// without the command it falls back to the original single pickup. Protocol: metin2-server docs/FEATURE-PICKUP.md.
|
||||
static const char c_szPickupScript[] = R"PY(# -*- coding: utf-8 -*-
|
||||
import app
|
||||
import chat
|
||||
import game
|
||||
import grp
|
||||
import net
|
||||
import ui
|
||||
import weakref
|
||||
from mt_biolog import Action, Text, L
|
||||
from mt_wiki import B
|
||||
|
||||
g_window=None
|
||||
g_entry=None
|
||||
CONFIG='mt_pickup.cfg'
|
||||
ALL=255
|
||||
CATEGORIES=((1,u'金币'),(2,u'武器'),(4,u'防具/首饰'),(8,u'技能书'),(16,u'灵石'),(32,u'材料'),(64,u'时装'),(128,u'其他'))
|
||||
SEND_GAP=.5
|
||||
TIMEOUT=3.
|
||||
ERRORS={'rate':'操作过快','invalid':'参数无效','busy':'当前状态不能拾取'}
|
||||
|
||||
|
||||
def Number(text,low=0,high=4294967295):
|
||||
if not text.isdigit() or len(text)>10:raise ValueError(text)
|
||||
value=int(text)
|
||||
if not low<=value<=high:raise ValueError(text)
|
||||
return value
|
||||
|
||||
|
||||
class Picker(object):
|
||||
# Protocol state only. send(text) posts a chat command, now() is seconds.
|
||||
def __init__(self,send,now,listener=None):
|
||||
self.send=send;self.now=now;self.listener=listener
|
||||
self.enabled=True;self.mask=ALL;self.waiting=None;self.nextSend=0
|
||||
self.unsupported=False;self.result=None;self.error=None
|
||||
|
||||
def Press(self):
|
||||
# True when the press was handled here; False means use the original single pickup.
|
||||
self.Tick()
|
||||
if not self.enabled or self.unsupported:return False
|
||||
now=self.now()
|
||||
if self.waiting is None and now>=self.nextSend:
|
||||
self.send('/mt_pickup 1 %d'%self.mask);self.waiting=now+TIMEOUT;self.nextSend=now+SEND_GAP
|
||||
return True
|
||||
|
||||
def Tick(self):
|
||||
if self.waiting is not None and self.now()>=self.waiting:
|
||||
self.waiting=None;self.unsupported=True;self.Notify('unsupported')
|
||||
|
||||
def Notify(self,kind):
|
||||
if self.listener:self.listener(kind)
|
||||
|
||||
def Receive(self,line):
|
||||
if not line.startswith('MTPU1 '):return False
|
||||
words=line.split()
|
||||
try:
|
||||
if words[1]=='done' and len(words)==5:
|
||||
found,picked,failed=[Number(w,0,1000) for w in words[2:]]
|
||||
self.result=dict(found=found,picked=picked,failed=failed);self.error=None;kind='done'
|
||||
elif words[1]=='error' and len(words)==3 and words[2] in ERRORS:self.error=words[2];kind='error'
|
||||
else:return True
|
||||
except ValueError:return True
|
||||
self.waiting=None;self.unsupported=False;self.Notify(kind)
|
||||
return True
|
||||
|
||||
def Load(self,text):
|
||||
try:
|
||||
enabled,mask=[Number(w) for w in text.split()]
|
||||
if enabled in (0,1) and 1<=mask<=ALL:self.enabled=enabled==1;self.mask=mask
|
||||
except ValueError:pass
|
||||
|
||||
def Dump(self):return '%d %d'%(int(self.enabled),self.mask)
|
||||
|
||||
def Toggle(self,bit):
|
||||
mask=self.mask^bit
|
||||
if mask:self.mask=mask # at least one category stays on
|
||||
|
||||
|
||||
def LoadConfig(picker):
|
||||
try:
|
||||
f=open(CONFIG,'r');text=f.read();f.close();picker.Load(text)
|
||||
except (IOError,OSError):pass
|
||||
|
||||
|
||||
def SaveConfig(picker):
|
||||
try:
|
||||
f=open(CONFIG,'w');f.write(picker.Dump());f.close()
|
||||
except (IOError,OSError):pass
|
||||
|
||||
|
||||
class PickupWindow(ui.Window):
|
||||
def __init__(self,picker):
|
||||
ui.Window.__init__(self);self.SetWindowName('PickupWindow');self.AddFlag('float');self.AddFlag('movable')
|
||||
self.picker=picker;self.SetSize(332,346)
|
||||
self.heading=Text(self,18,18,'批量拾取',0xffffd68b)
|
||||
self.closeButton=Action(self,256,6,60,'关闭',self.Hide)
|
||||
self.enableButton=Action(self,18,52,296,'',self.ToggleEnabled)
|
||||
self.categoryButtons=[Action(self,18+(i%2)*152,108+(i//2)*52,144,'',lambda bit=bit:self.ToggleCategory(bit))
|
||||
for i,(bit,name) in enumerate(CATEGORIES)]
|
||||
self.status=Text(self,18,322,'',0xffc3b7a1)
|
||||
self.Refresh();self.Hide()
|
||||
|
||||
def Buttons(self):return [self.closeButton,self.enableButton]+self.categoryButtons
|
||||
|
||||
def Open(self):self.Refresh();self.SetCenterPosition();self.Show();self.SetTop()
|
||||
|
||||
def ToggleEnabled(self):
|
||||
self.picker.enabled=not self.picker.enabled;self.picker.unsupported=False;SaveConfig(self.picker);self.Refresh()
|
||||
|
||||
def ToggleCategory(self,bit):self.picker.Toggle(bit);SaveConfig(self.picker);self.Refresh()
|
||||
|
||||
def Refresh(self):
|
||||
p=self.picker
|
||||
self.enableButton.SetText(L('拾取键(Z):批量拾取 已开启' if p.enabled else '拾取键(Z):批量拾取 已关闭(单个拾取)'))
|
||||
for button,(bit,name) in zip(self.categoryButtons,CATEGORIES):
|
||||
button.SetText(L(B(u'【%s】'%name if p.mask&bit else name)))
|
||||
button.SetEnabled(p.enabled)
|
||||
self.status.SetText(L(self.StatusText()))
|
||||
|
||||
def StatusText(self):
|
||||
p=self.picker
|
||||
if p.unsupported:return '!服务器尚未启用批量拾取,已改用单个拾取'
|
||||
if p.error:return '!'+ERRORS[p.error]
|
||||
if p.result:
|
||||
r=p.result;text='上次:附近 %d 件,拾取 %d 件'%(r['found'],r['picked'])
|
||||
return text+(',%d 件未能拾取'%r['failed'] if r['failed'] else '')
|
||||
return '只拾取自己的物品,范围与单个拾取相同'
|
||||
|
||||
def OnRender(self):
|
||||
x,y=self.GetGlobalPosition();grp.SetColor(0xf51b1916);grp.RenderBar(x,y,self.GetWidth(),self.GetHeight());grp.SetColor(0xff9b7b48);grp.RenderBox(x,y,self.GetWidth(),self.GetHeight())
|
||||
|
||||
def OnUpdate(self):self.picker.Tick()
|
||||
|
||||
def OnPressEscapeKey(self):self.Hide();return True
|
||||
|
||||
def Destroy(self):
|
||||
self.Hide()
|
||||
for b in self.Buttons():b.event=None
|
||||
|
||||
|
||||
class Entry(Action):
|
||||
def __init__(self,window):
|
||||
Action.__init__(self,None,0,0,64,'拾取',Toggle)
|
||||
self.minimap=weakref.proxy(window.interface.wndMiniMap);self.SetWindowName('PickupEntry');self.OnUpdate()
|
||||
|
||||
def OnUpdate(self):
|
||||
x,y=self.minimap.GetGlobalPosition();self.SetPosition(max(4,x-68),y+200)
|
||||
|
||||
|
||||
def OnPicker(kind):
|
||||
if kind=='unsupported':chat.AppendChat(chat.CHAT_TYPE_INFO,L('服务器尚未启用批量拾取,已改用单个拾取'))
|
||||
if g_window:g_window.Refresh()
|
||||
|
||||
|
||||
g_picker=Picker(net.SendChatPacket,app.GetTime,OnPicker)
|
||||
LoadConfig(g_picker)
|
||||
|
||||
|
||||
def Toggle():
|
||||
if g_window:
|
||||
if g_window.IsShow():g_window.Hide()
|
||||
else:g_window.Open()
|
||||
|
||||
|
||||
_open=game.GameWindow.Open
|
||||
_close=game.GameWindow.Close
|
||||
_command=game.GameWindow.BINARY_ServerCommand_Run
|
||||
_pick=game.GameWindow.PickUpItem
|
||||
|
||||
def Open(self):
|
||||
global g_window,g_entry
|
||||
_open(self);g_picker.waiting=None;g_window=PickupWindow(g_picker);g_entry=Entry(self)
|
||||
|
||||
def Close(self):
|
||||
global g_window,g_entry
|
||||
if g_entry:g_entry.Hide();g_entry.event=None;g_entry=None
|
||||
if g_window:g_window.Destroy();g_window=None
|
||||
_close(self)
|
||||
|
||||
def Command(self,line):
|
||||
if g_picker.Receive(line):return 1
|
||||
return _command(self,line)
|
||||
|
||||
def PickUpItem(self):
|
||||
if not g_picker.Press():_pick(self)
|
||||
|
||||
game.GameWindow.Open=Open
|
||||
game.GameWindow.Close=Close
|
||||
game.GameWindow.BINARY_ServerCommand_Run=Command
|
||||
game.GameWindow.PickUpItem=PickUpItem
|
||||
)PY";
|
||||
@@ -999,6 +999,10 @@ namespace PythonBoot
|
||||
#include "DungeonScript.inc"
|
||||
#include "CalendarScript.inc"
|
||||
#include "WikiEntryScript.inc"
|
||||
#include "SwitchbotScript.inc"
|
||||
#include "PickupScript.inc"
|
||||
#include "DisplayScript.inc"
|
||||
#include "ChannelScript.inc"
|
||||
|
||||
static void install_script_module(const char* c_szModule, const char* c_szScript)
|
||||
{
|
||||
@@ -1072,6 +1076,10 @@ bool RunMainScript(const char* lpCmdLine, std::string* error)
|
||||
install_script_module("mt_dungeons", c_szDungeonScript);
|
||||
install_script_module("mt_calendar", c_szCalendarScript);
|
||||
install_script_module("mt_wiki_entries", c_szWikiEntryScript);
|
||||
install_script_module("mt_switchbot", c_szSwitchbotScript);
|
||||
install_script_module("mt_pickup", c_szPickupScript);
|
||||
install_script_module("mt_display", c_szDisplayScript);
|
||||
install_script_module("mt_channel", c_szChannelScript);
|
||||
if (g_touch_input)
|
||||
install_script_module("mt_mobile_hud", c_szMobileHUDScript);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,371 @@
|
||||
// PORT: AVA2-style automatic attribute change (uiswitchbot.py), driven by the server's /mt_switchbot
|
||||
// command. Every roll runs on the server through the original change-attribute scroll path; this window
|
||||
// only picks the item, scroll and targets and shows progress. Protocol: metin2-server docs/FEATURE-SWITCHBOT.md.
|
||||
static const char c_szSwitchbotScript[] = R"PY(# -*- coding: utf-8 -*-
|
||||
import app
|
||||
import chat
|
||||
import game
|
||||
import grp
|
||||
import item
|
||||
import net
|
||||
import player
|
||||
import ui
|
||||
import uiToolTip
|
||||
import wndMgr
|
||||
import weakref
|
||||
from mt_biolog import Action, Text, L
|
||||
from mt_wiki import B, U
|
||||
|
||||
g_window=None
|
||||
g_entry=None
|
||||
USE_CHANGE_ATTRIBUTE=18 # CItemData::EUseSubTypes; the server re-checks the scroll subtype.
|
||||
LIMITS=(10,50,100,200,500,1000)
|
||||
MAX_TARGETS=5
|
||||
SEND_GAP=.3
|
||||
TIMEOUT=4.
|
||||
REASONS={'running':'洗练中','matched':'已获得目标属性','limit':'已达到次数上限','no_scroll':'洗练道具已用完',
|
||||
'item_gone':'物品已移动、装备或交易,已停止','rejected':'服务器拒绝了本次洗练','busy':'交易/商店/仓库/合成界面打开,已停止',
|
||||
'stopped':'已手动停止','idle':'未运行'}
|
||||
ERRORS={'rate':'操作过快,请稍后','invalid':'参数无效','item':'物品不存在','equipped':'请先卸下装备或结束交易','no_attr':'该物品不能洗练',
|
||||
'scroll':'没有可用的洗练道具','target':'目标属性超出可洗范围','running':'已有洗练在进行','busy':'当前状态不能洗练',
|
||||
'unsupported':'服务器尚未启用自动洗练'}
|
||||
|
||||
|
||||
def Number(text,low=0,high=4294967295):
|
||||
if not text.isdigit() or len(text)>10:raise ValueError(text)
|
||||
value=int(text)
|
||||
if not low<=value<=high:raise ValueError(text)
|
||||
return value
|
||||
|
||||
|
||||
class Bot(object):
|
||||
# Protocol state only; the window renders it. send(text) posts a chat command, now() is seconds.
|
||||
def __init__(self,send,now,listener=None):
|
||||
self.send=send;self.now=now;self.listener=listener
|
||||
self.queue=[];self.nextSend=0;self.waiting=None
|
||||
self.allowed={};self.loading=None;self.state=None;self.error=None;self.unsupported=False
|
||||
|
||||
def Enqueue(self,verb,text):
|
||||
if verb=='attrs' and self.waiting and self.waiting[2]==text:return
|
||||
self.queue=[q for q in self.queue if not (verb=='attrs' and q[0]=='attrs')]
|
||||
if len(self.queue)<4:self.queue.append((verb,text))
|
||||
self.Tick()
|
||||
|
||||
def RequestAttrs(self,cell):
|
||||
self.Enqueue('attrs','/mt_switchbot 1 attrs %d'%cell)
|
||||
|
||||
def Start(self,cell,scroll,limit,alternatives):
|
||||
groups=[a for a in alternatives if a]
|
||||
if not groups or len(groups)>2 or not 1<=limit<=1000:return 'invalid'
|
||||
allowed=dict(self.allowed.get(cell,{}).get('rows',()))
|
||||
parts=['/mt_switchbot 1 start %d %d %d'%(cell,scroll,limit)]
|
||||
for targets in groups:
|
||||
if len(targets)>MAX_TARGETS or len(set(a for a,v in targets))!=len(targets):return 'invalid'
|
||||
parts.append(str(len(targets)))
|
||||
for apply,value in targets:
|
||||
if apply not in allowed or not 1<=value<=allowed[apply]:return 'target'
|
||||
parts.append('%d %d'%(apply,value))
|
||||
self.error=None;self.Enqueue('start',' '.join(parts));return None
|
||||
|
||||
def Stop(self):self.Enqueue('stop','/mt_switchbot 1 stop')
|
||||
def Status(self):self.Enqueue('status','/mt_switchbot 1 status')
|
||||
def Running(self):return bool(self.state and self.state['active'])
|
||||
|
||||
def Tick(self):
|
||||
now=self.now()
|
||||
if self.waiting and now>=self.waiting[1]:
|
||||
self.waiting=None;self.queue=[];self.loading=None;self.unsupported=True;self.error='unsupported';self.Notify('error')
|
||||
if self.queue and not self.waiting and now>=self.nextSend:
|
||||
verb,text=self.queue.pop(0);self.send(text);self.nextSend=now+SEND_GAP
|
||||
self.waiting=(verb,now+TIMEOUT,text)
|
||||
|
||||
def Answered(self,verb):
|
||||
if self.waiting and (self.waiting[0]==verb or verb in ('state','error')):self.waiting=None
|
||||
self.unsupported=False
|
||||
|
||||
def Notify(self,kind):
|
||||
if self.listener:self.listener(kind)
|
||||
|
||||
def Receive(self,line):
|
||||
if not line.startswith('MTSB1 '):return False
|
||||
words=line.split()
|
||||
try:self.Parse(words[1:])
|
||||
except (ValueError,IndexError,KeyError):self.loading=None
|
||||
return True
|
||||
|
||||
def Parse(self,words):
|
||||
kind=words[0]
|
||||
if kind=='attrs':
|
||||
self.loading=dict(cell=Number(words[1]),vnum=Number(words[2]),count=Number(words[3],0,255),rows=[])
|
||||
elif kind=='attr':
|
||||
row=self.loading;index=Number(words[1])
|
||||
if not row or index!=len(row['rows']) or index>=row['count']:raise ValueError('order')
|
||||
row['rows'].append((Number(words[2],0,255),Number(words[3],1,2147483647)))
|
||||
elif kind=='attrs_end':
|
||||
row=self.loading;self.loading=None
|
||||
if not row or Number(words[1])!=row['cell'] or Number(words[2])!=row['count'] or len(row['rows'])!=row['count']:
|
||||
raise ValueError('partial')
|
||||
self.allowed[row['cell']]=row;self.Answered('attrs');self.Notify('attrs')
|
||||
elif kind=='state':
|
||||
if len(words)!=9 or words[8] not in REASONS:raise ValueError('state')
|
||||
self.state=dict(active=Number(words[1],0,1)==1,cell=Number(words[2]),vnum=Number(words[3]),rolls=Number(words[4]),
|
||||
limit=Number(words[5]),scroll=Number(words[6]),scrolls=Number(words[7]),reason=words[8])
|
||||
self.Answered('state');self.Notify('state')
|
||||
elif kind=='error':
|
||||
if len(words)!=3 or words[2] not in ERRORS:raise ValueError('error')
|
||||
if words[1]=='attrs':self.loading=None
|
||||
self.error=words[2];self.Answered('error');self.Notify('error')
|
||||
|
||||
|
||||
def ItemName(vnum):
|
||||
item.SelectItem(vnum);return item.GetItemName()
|
||||
|
||||
|
||||
def AffectText(apply,value):
|
||||
affect=getattr(uiToolTip.ItemToolTip,'AFFECT_DICT',{}).get(apply)
|
||||
try:
|
||||
if affect:return affect(value)
|
||||
except (TypeError,ValueError):pass
|
||||
return L(B(u'属性#%d +%d'%(apply,value)))
|
||||
|
||||
|
||||
def Step(maximum):return max(1,maximum//5)
|
||||
|
||||
|
||||
class SwitchbotWindow(ui.Window):
|
||||
def __init__(self):
|
||||
ui.Window.__init__(self);self.SetWindowName('SwitchbotWindow');self.AddFlag('float');self.AddFlag('movable')
|
||||
self.bot=Bot(net.SendChatPacket,app.GetTime,self.OnBot)
|
||||
self.items=[];self.itemIndex=0;self.scrolls=[];self.scrollIndex=0;self.limitIndex=2
|
||||
self.alternatives=[[],[]];self.alt=0;self.picking=False;self.pickPage=0;self.dimensions=None;self.nextScan=0
|
||||
self.heading=Text(self,18,18,'自动洗练',0xffffd68b)
|
||||
self.closeButton=Action(self,0,6,60,'关闭',self.Hide)
|
||||
self.itemPrev=Action(self,18,58,48,'<',lambda:self.Cycle('item',-1));self.itemNext=Action(self,0,58,48,'>',lambda:self.Cycle('item',1))
|
||||
self.itemText=Text(self,80,82,'')
|
||||
self.scrollPrev=Action(self,18,110,48,'<',lambda:self.Cycle('scroll',-1));self.scrollNext=Action(self,0,110,48,'>',lambda:self.Cycle('scroll',1))
|
||||
self.scrollText=Text(self,80,134,'')
|
||||
self.limitButton=Action(self,0,110,110,'',self.NextLimit)
|
||||
self.altButtons=[Action(self,18+i*104,162,96,'方案一' if i==0 else '方案二',lambda i=i:self.SelectAlt(i)) for i in range(2)]
|
||||
self.addButton=Action(self,0,162,110,'添加属性',self.TogglePick)
|
||||
self.rows=[]
|
||||
for i in range(MAX_TARGETS):
|
||||
y=214+i*46
|
||||
self.rows.append(dict(text=Text(self,24,y+22,''),minus=Action(self,0,y,44,'-',lambda i=i:self.Adjust(i,-1)),
|
||||
plus=Action(self,0,y,44,'+',lambda i=i:self.Adjust(i,1)),remove=Action(self,0,y,44,'×',lambda i=i:self.Remove(i)),
|
||||
pick=Action(self,18,y,100,'',lambda i=i:self.Pick(i))))
|
||||
self.pickPrev=Action(self,18,0,80,'上一页',lambda:self.PickPage(-1));self.pickNext=Action(self,0,0,80,'下一页',lambda:self.PickPage(1))
|
||||
self.startButton=Action(self,18,0,120,'开始洗练',self.Start);self.stopButton=Action(self,146,0,120,'停止',self.bot.Stop)
|
||||
self.status=Text(self,18,0,'',0xffc3b7a1);self.current=Text(self,18,0,'',0xffefdfc3)
|
||||
self.Reflow();self.Hide()
|
||||
|
||||
def Buttons(self):
|
||||
rows=[b for r in self.rows for b in (r['minus'],r['plus'],r['remove'],r['pick'])]
|
||||
return [self.closeButton,self.itemPrev,self.itemNext,self.scrollPrev,self.scrollNext,self.limitButton,self.addButton,
|
||||
self.pickPrev,self.pickNext,self.startButton,self.stopButton]+self.altButtons+rows
|
||||
|
||||
def Open(self):
|
||||
self.Reflow();self.Scan();self.SetCenterPosition();self.Show();self.SetTop();self.bot.Status();self.RequestAttrs()
|
||||
|
||||
def Scan(self):
|
||||
items=[];scrolls={}
|
||||
for cell in range(player.INVENTORY_PAGE_SIZE*player.INVENTORY_PAGE_COUNT):
|
||||
vnum=player.GetItemIndex(player.INVENTORY,cell)
|
||||
if not vnum:continue
|
||||
item.SelectItem(vnum);kind=item.GetItemType()
|
||||
if kind==item.ITEM_TYPE_USE and item.GetItemSubType()==USE_CHANGE_ATTRIBUTE:
|
||||
scrolls[vnum]=scrolls.get(vnum,0)+player.GetItemCount(player.INVENTORY,cell)
|
||||
elif kind in (item.ITEM_TYPE_WEAPON,item.ITEM_TYPE_ARMOR) and any(player.GetItemAttribute(player.INVENTORY,cell,i)[0] for i in range(5)):
|
||||
items.append((cell,vnum))
|
||||
selected=self.Selected();scroll=self.Scroll();state=self.bot.state
|
||||
if state and state['active'] and (state['cell'],state['vnum']) in items:
|
||||
# The server binds the bot to the item ID and reports its current cell; follow it after a move.
|
||||
if selected and selected[0] in self.bot.allowed and selected[1]==state['vnum']:
|
||||
self.bot.allowed[state['cell']]=dict(self.bot.allowed[selected[0]],cell=state['cell'])
|
||||
selected=(state['cell'],state['vnum'])
|
||||
self.items=items;self.scrolls=sorted(scrolls.items())
|
||||
self.itemIndex=next((i for i,v in enumerate(items) if v==selected),
|
||||
next((i for i,v in enumerate(items) if selected and v[1]==selected[1]),min(self.itemIndex,max(0,len(items)-1))))
|
||||
self.scrollIndex=next((i for i,v in enumerate(self.scrolls) if v[0]==scroll),min(self.scrollIndex,max(0,len(self.scrolls)-1)))
|
||||
self.nextScan=app.GetTime()+1
|
||||
if self.Selected()!=selected:self.alternatives=[[],[]];self.RequestAttrs()
|
||||
|
||||
def Selected(self):return self.items[self.itemIndex] if self.items else None
|
||||
def Scroll(self):return self.scrolls[self.scrollIndex][0] if self.scrolls else 0
|
||||
|
||||
def RequestAttrs(self):
|
||||
selected=self.Selected()
|
||||
if selected and (self.bot.allowed.get(selected[0],{}).get('vnum')!=selected[1]):self.bot.RequestAttrs(selected[0])
|
||||
|
||||
def Allowed(self):
|
||||
selected=self.Selected()
|
||||
data=self.bot.allowed.get(selected[0]) if selected else None
|
||||
return data['rows'] if data and data['vnum']==selected[1] else None
|
||||
|
||||
def Cycle(self,kind,step):
|
||||
if self.bot.Running():return
|
||||
if kind=='item' and self.items:
|
||||
self.itemIndex=(self.itemIndex+step)%len(self.items);self.alternatives=[[],[]];self.picking=False;self.RequestAttrs()
|
||||
elif kind=='scroll' and self.scrolls:self.scrollIndex=(self.scrollIndex+step)%len(self.scrolls)
|
||||
self.Refresh()
|
||||
|
||||
def NextLimit(self):
|
||||
if not self.bot.Running():self.limitIndex=(self.limitIndex+1)%len(LIMITS);self.Refresh()
|
||||
|
||||
def SelectAlt(self,index):self.alt=index;self.picking=False;self.Refresh()
|
||||
|
||||
def TogglePick(self):
|
||||
if self.bot.Running() or self.Allowed() is None:return
|
||||
self.picking=not self.picking;self.pickPage=0;self.Refresh()
|
||||
|
||||
def Candidates(self):
|
||||
used=set(a for a,v in self.alternatives[self.alt])
|
||||
return [r for r in self.Allowed() or () if r[0] not in used]
|
||||
|
||||
def PickPage(self,step):self.pickPage+=step;self.Refresh()
|
||||
|
||||
def Pick(self,index):
|
||||
rows=self.Candidates()[self.pickPage*MAX_TARGETS:]
|
||||
if index<len(rows) and len(self.alternatives[self.alt])<MAX_TARGETS:
|
||||
self.alternatives[self.alt].append(list(rows[index]));self.picking=False
|
||||
self.Refresh()
|
||||
|
||||
def Maximum(self,apply):return dict(self.Allowed() or ()).get(apply,1)
|
||||
|
||||
def Adjust(self,index,direction):
|
||||
target=self.alternatives[self.alt][index];maximum=self.Maximum(target[0])
|
||||
target[1]=max(1,min(maximum,target[1]+direction*Step(maximum)));self.Refresh()
|
||||
|
||||
def Remove(self,index):del self.alternatives[self.alt][index];self.Refresh()
|
||||
|
||||
def Start(self):
|
||||
selected=self.Selected()
|
||||
if not selected or self.bot.Running():return
|
||||
if not self.Scroll():self.bot.error='scroll';self.Refresh();return
|
||||
error=self.bot.Start(selected[0],self.Scroll(),LIMITS[self.limitIndex],[[tuple(t) for t in a] for a in self.alternatives])
|
||||
if error:self.bot.error='target' if error=='target' else 'invalid'
|
||||
self.Refresh()
|
||||
|
||||
def OnBot(self,kind):
|
||||
state=self.bot.state
|
||||
if kind=='state' and state and not state['active'] and state['reason'] not in ('idle',):
|
||||
message=u'自动洗练:'+U(REASONS[state['reason']])+u'(%d 次)'%state['rolls']
|
||||
chat.AppendChat(chat.CHAT_TYPE_INFO,L(B(message)))
|
||||
if state['reason']=='matched' and not self.IsShow():self.Open()
|
||||
if kind=='state':self.nextScan=0
|
||||
self.Refresh()
|
||||
|
||||
def Refresh(self):
|
||||
running=self.bot.Running();allowed=self.Allowed();selected=self.Selected()
|
||||
if selected:self.itemText.SetText(ItemName(selected[1])+L(B(u' (%d / %d)'%(self.itemIndex+1,len(self.items)))))
|
||||
else:self.itemText.SetText(L('背包中没有可洗练的武器或防具'))
|
||||
if self.scrolls:
|
||||
vnum,count=self.scrolls[self.scrollIndex];self.scrollText.SetText(ItemName(vnum)+L(B(u' ×%d'%count)))
|
||||
else:self.scrollText.SetText(L('背包中没有洗练道具'))
|
||||
self.limitButton.SetText(L(B(u'上限 %d 次'%LIMITS[self.limitIndex])))
|
||||
for i,b in enumerate(self.altButtons):b.SetText(L(B((u'【%s %d】' if i==self.alt else u'%s %d')%(u'方案一' if i==0 else u'方案二',len(self.alternatives[i])))))
|
||||
self.addButton.SetText(L('返回' if self.picking else '添加属性'))
|
||||
for b in (self.itemPrev,self.itemNext,self.scrollPrev,self.scrollNext,self.limitButton):b.SetEnabled(not running)
|
||||
self.addButton.SetEnabled(not running and allowed is not None and (self.picking or len(self.alternatives[self.alt])<MAX_TARGETS))
|
||||
targets=self.alternatives[self.alt];candidates=self.Candidates() if self.picking else []
|
||||
pages=max(1,(len(candidates)+MAX_TARGETS-1)//MAX_TARGETS);self.pickPage=max(0,min(self.pickPage,pages-1))
|
||||
for i,row in enumerate(self.rows):
|
||||
for key in ('text','minus','plus','remove','pick'):row[key].Hide()
|
||||
if self.picking:
|
||||
index=self.pickPage*MAX_TARGETS+i
|
||||
if index<len(candidates):
|
||||
row['pick'].SetText(AffectText(*candidates[index]));row['pick'].Show()
|
||||
elif i<len(targets):
|
||||
apply,value=targets[i];row['text'].SetText(L('≥ ')+AffectText(apply,value));row['text'].Show()
|
||||
for key in ('minus','plus','remove'):row[key].SetEnabled(not running);row[key].Show()
|
||||
for b in (self.pickPrev,self.pickNext):
|
||||
if self.picking and pages>1:b.Show()
|
||||
else:b.Hide()
|
||||
self.pickPrev.SetEnabled(self.pickPage>0);self.pickNext.SetEnabled(self.pickPage+1<pages)
|
||||
self.startButton.SetEnabled(not running and bool(selected) and any(self.alternatives));self.stopButton.SetEnabled(running)
|
||||
self.status.SetText(L(B(self.StatusText(allowed))));self.current.SetText(self.CurrentText(selected))
|
||||
|
||||
def StatusText(self,allowed):
|
||||
state=self.bot.state
|
||||
if self.bot.error:return u'!'+U(ERRORS[self.bot.error])
|
||||
if self.Selected() and allowed is None:return u'正在读取可洗属性…'
|
||||
if state and (state['active'] or state['reason']!='idle'):
|
||||
return u'%s · %d / %d 次 · 剩余道具 %d'%(U(REASONS[state['reason']]),state['rolls'],state['limit'],state['scrolls'])
|
||||
return u'任一方案的属性全部达标即停止;只看前 5 条普通属性'
|
||||
|
||||
def CurrentText(self,selected):
|
||||
if not selected:return ''
|
||||
parts=[]
|
||||
for i in range(5):
|
||||
apply,value=player.GetItemAttribute(player.INVENTORY,selected[0],i)
|
||||
if apply:parts.append(AffectText(apply,value))
|
||||
return ' / '.join(parts)
|
||||
|
||||
def Reflow(self):
|
||||
dims=(wndMgr.GetScreenWidth(),wndMgr.GetScreenHeight())
|
||||
if dims==self.dimensions:return
|
||||
self.dimensions=dims;width=min(600,max(480,dims[0]-16));height=min(560,max(400,dims[1]-8));self.SetSize(width,height)
|
||||
self.closeButton.SetPosition(width-76,6);self.itemNext.SetPosition(width-66,58);self.limitButton.SetPosition(width-128,110)
|
||||
self.scrollNext.SetPosition(width-184,110);self.addButton.SetPosition(width-128,162)
|
||||
for row in self.rows:
|
||||
x,y=row['minus'].GetLocalPosition()
|
||||
row['minus'].SetPosition(width-166,y);row['plus'].SetPosition(width-116,y);row['remove'].SetPosition(width-66,y)
|
||||
row['pick'].SetSize(width-36,44);row['pick'].label.SetPosition((width-36)//2,22)
|
||||
bottom=height-104
|
||||
self.pickPrev.SetPosition(18,bottom);self.pickNext.SetPosition(width-98,bottom)
|
||||
self.startButton.SetPosition(18,bottom);self.stopButton.SetPosition(146,bottom)
|
||||
self.status.SetPosition(18,height-46);self.current.SetPosition(18,height-22)
|
||||
self.SetCenterPosition();self.Refresh()
|
||||
|
||||
def OnUpdate(self):
|
||||
self.Reflow();self.bot.Tick()
|
||||
if self.IsShow() and app.GetTime()>=self.nextScan:self.Scan();self.Refresh()
|
||||
|
||||
def OnRender(self):
|
||||
x,y=self.GetGlobalPosition();grp.SetColor(0xf51b1916);grp.RenderBar(x,y,self.GetWidth(),self.GetHeight());grp.SetColor(0xff9b7b48);grp.RenderBox(x,y,self.GetWidth(),self.GetHeight())
|
||||
|
||||
def OnPressEscapeKey(self):self.Hide();return True
|
||||
|
||||
def Destroy(self):
|
||||
self.Hide();self.bot.listener=None
|
||||
for b in self.Buttons():b.event=None
|
||||
|
||||
|
||||
class Entry(Action):
|
||||
def __init__(self,window):
|
||||
Action.__init__(self,None,0,0,64,'洗练',Toggle)
|
||||
self.minimap=weakref.proxy(window.interface.wndMiniMap);self.SetWindowName('SwitchbotEntry');self.OnUpdate()
|
||||
|
||||
def OnUpdate(self):
|
||||
x,y=self.minimap.GetGlobalPosition();self.SetPosition(max(4,x-68),y+148)
|
||||
|
||||
|
||||
def Toggle():
|
||||
if g_window:
|
||||
if g_window.IsShow():g_window.Hide()
|
||||
else:g_window.Open()
|
||||
|
||||
|
||||
_open=game.GameWindow.Open
|
||||
_close=game.GameWindow.Close
|
||||
_command=game.GameWindow.BINARY_ServerCommand_Run
|
||||
|
||||
def Open(self):
|
||||
global g_window,g_entry
|
||||
_open(self);g_window=SwitchbotWindow();g_entry=Entry(self)
|
||||
|
||||
def Close(self):
|
||||
global g_window,g_entry
|
||||
if g_entry:g_entry.Hide();g_entry.event=None;g_entry=None
|
||||
if g_window:g_window.Destroy();g_window=None
|
||||
_close(self)
|
||||
|
||||
def Command(self,line):
|
||||
if line.startswith('MTSB1 '):
|
||||
if g_window:g_window.bot.Receive(line)
|
||||
return 1
|
||||
return _command(self,line)
|
||||
|
||||
game.GameWindow.Open=Open
|
||||
game.GameWindow.Close=Close
|
||||
game.GameWindow.BINARY_ServerCommand_Run=Command
|
||||
)PY";
|
||||
@@ -316,6 +316,14 @@ if(BUILD_TESTING AND CMAKE_SYSTEM_NAME STREQUAL CMAKE_HOST_SYSTEM_NAME)
|
||||
COMMAND ${MT_WIKI_PYTHON3} ${PROJECT_SOURCE_DIR}/tests/wiki/test_timers.py)
|
||||
add_test(NAME port.feature_service
|
||||
COMMAND ${MT_WIKI_PYTHON3} ${PROJECT_SOURCE_DIR}/tests/wiki/test_service.py)
|
||||
add_test(NAME port.switchbot
|
||||
COMMAND ${MT_WIKI_PYTHON3} ${PROJECT_SOURCE_DIR}/tests/wiki/test_switchbot.py)
|
||||
add_test(NAME port.pickup
|
||||
COMMAND ${MT_WIKI_PYTHON3} ${PROJECT_SOURCE_DIR}/tests/wiki/test_pickup.py)
|
||||
add_test(NAME port.display
|
||||
COMMAND ${MT_WIKI_PYTHON3} ${PROJECT_SOURCE_DIR}/tests/wiki/test_display.py)
|
||||
add_test(NAME port.channel
|
||||
COMMAND ${MT_WIKI_PYTHON3} ${PROJECT_SOURCE_DIR}/tests/wiki/test_channel.py)
|
||||
endif()
|
||||
# Offline locale data builder: retains 40250 proto layout and gameplay fields.
|
||||
add_executable(locale_proto_patch ${PROJECT_SOURCE_DIR}/tests/port/locale_proto_patch.cpp)
|
||||
|
||||
@@ -252,6 +252,17 @@ void CEffectManager::DeactiveEffectInstance(DWORD dwInstanceIndex)
|
||||
pEffectInstance->SetDeactive();
|
||||
}
|
||||
|
||||
// PORT: AVA2 ENABLE_GRAPHIC_ON_OFF (display options effect level).
|
||||
void CEffectManager::ActiveEffectInstance(DWORD dwInstanceIndex)
|
||||
{
|
||||
TEffectInstanceMap::iterator itor = m_kEftInstMap.find(dwInstanceIndex);
|
||||
|
||||
if (itor == m_kEftInstMap.end())
|
||||
return;
|
||||
|
||||
itor->second->SetActive();
|
||||
}
|
||||
|
||||
void CEffectManager::CreateUnsafeEffectInstance(DWORD dwEffectDataID, CEffectInstance ** ppEffectInstance)
|
||||
{
|
||||
CEffectData * pEffect;
|
||||
|
||||
@@ -47,6 +47,7 @@ class CEffectManager : public CScreen, public CSingleton<CEffectManager>
|
||||
BOOL SelectEffectInstance(DWORD dwInstanceIndex);
|
||||
bool DestroyEffectInstance(DWORD dwInstanceIndex);
|
||||
void DeactiveEffectInstance(DWORD dwInstanceIndex);
|
||||
void ActiveEffectInstance(DWORD dwInstanceIndex); // PORT: AVA2 ENABLE_GRAPHIC_ON_OFF
|
||||
|
||||
void SetEffectTextures(DWORD dwID, std::vector<std::string> textures);
|
||||
void SetEffectInstancePosition(const D3DXVECTOR3 & c_rv3Position);
|
||||
|
||||
@@ -496,6 +496,9 @@ class CActorInstance : public IActorInstance, public IFlyTargetableObject
|
||||
float GetHeight();
|
||||
void ShowAllAttachingEffect();
|
||||
void HideAllAttachingEffect();
|
||||
// PORT: AVA2 ENABLE_GRAPHIC_ON_OFF. Deactivates (not hides) attached effects, so it does not fight
|
||||
// the assassin invisibility Show/Hide; effects attached while off start deactivated.
|
||||
void SetAttachingEffectShown(bool bShown);
|
||||
void ClearAttachingEffect();
|
||||
|
||||
// Fishing
|
||||
@@ -793,6 +796,7 @@ class CActorInstance : public IActorInstance, public IFlyTargetableObject
|
||||
// Attached Effect
|
||||
std::list<TAttachingEffect> m_AttachingEffectList;
|
||||
bool m_bEffectInitialized;
|
||||
bool m_bAttachingEffectShown = true;
|
||||
|
||||
// material color
|
||||
DWORD m_dwMtrlColor;
|
||||
|
||||
@@ -294,6 +294,8 @@ DWORD CActorInstance::AttachEffectByID(DWORD dwParentPartIndex, const char * c_p
|
||||
ae.iBoneIndex = -1;
|
||||
}
|
||||
|
||||
if (!m_bAttachingEffectShown)
|
||||
rkEftMgr.DeactiveEffectInstance(ae.dwEffectIndex);
|
||||
m_AttachingEffectList.push_back(ae);
|
||||
|
||||
return ae.dwEffectIndex;
|
||||
@@ -472,6 +474,8 @@ void CActorInstance::RefreshActorInstance()
|
||||
|
||||
ae.iBoneIndex = iBoneIndex;
|
||||
|
||||
if (!m_bAttachingEffectShown)
|
||||
CEffectManager::Instance().DeactiveEffectInstance(ae.dwEffectIndex);
|
||||
m_AttachingEffectList.push_back(ae);
|
||||
}
|
||||
break;
|
||||
@@ -593,6 +597,22 @@ void CActorInstance::HideAllAttachingEffect()
|
||||
}
|
||||
}
|
||||
|
||||
void CActorInstance::SetAttachingEffectShown(bool bShown)
|
||||
{
|
||||
if (m_bAttachingEffectShown == bShown)
|
||||
return;
|
||||
|
||||
m_bAttachingEffectShown = bShown;
|
||||
CEffectManager& rkEftMgr = CEffectManager::Instance();
|
||||
for (const TAttachingEffect& ae : m_AttachingEffectList)
|
||||
{
|
||||
if (bShown)
|
||||
rkEftMgr.ActiveEffectInstance(ae.dwEffectIndex);
|
||||
else
|
||||
rkEftMgr.DeactiveEffectInstance(ae.dwEffectIndex);
|
||||
}
|
||||
}
|
||||
|
||||
void CActorInstance::__ClearAttachingEffect()
|
||||
{
|
||||
m_bEffectInitialized = false;
|
||||
|
||||
@@ -640,7 +640,13 @@ void CMapOutdoor::RenderPCBlocker()
|
||||
STATEMANAGER.SaveTransform(D3DTS_TEXTURE1, &m_matBuildingTransparent);
|
||||
STATEMANAGER.SetTexture(1, m_BuildingTransparentImageInstance.GetTexturePointer()->GetD3DTexture());
|
||||
|
||||
std::for_each(m_PCBlockerVector.begin(), m_PCBlockerVector.end(), FRenderPCBlocker());
|
||||
// PORT: a tree near the camera is drawn here as a PC blocker, outside RenderTree, so hiding
|
||||
// PART_TREE (mt_display) left it on screen. Skip it the same way RenderTree does.
|
||||
const bool bTreeVisible = IsVisiblePart(PART_TREE);
|
||||
FRenderPCBlocker kRenderPCBlocker;
|
||||
for (CGraphicObjectInstance * pInstance : m_PCBlockerVector)
|
||||
if (bTreeVisible || TREE_OBJECT != pInstance->GetType())
|
||||
kRenderPCBlocker(pInstance);
|
||||
|
||||
STATEMANAGER.SetTexture(1, NULL);
|
||||
STATEMANAGER.RestoreTransform(D3DTS_TEXTURE1);
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include "PythonNonPlayer.h"
|
||||
#include "PythonPlayer.h"
|
||||
#include "PythonCharacterManager.h"
|
||||
#include "PythonSystem.h"
|
||||
#include "AbstractPlayer.h"
|
||||
#include "AbstractApplication.h"
|
||||
#include "Packet.h"
|
||||
@@ -1868,6 +1869,7 @@ void CInstanceBase::Update()
|
||||
{
|
||||
++ms_dwUpdateCounter;
|
||||
|
||||
__UpdateEffectShown();
|
||||
StateProcess();
|
||||
m_GraphicThingInstance.PhysicsProcess();
|
||||
m_GraphicThingInstance.RotationProcess();
|
||||
@@ -2454,6 +2456,25 @@ bool CInstanceBase::__IsInViewFrustum()
|
||||
return m_GraphicThingInstance.isShow();
|
||||
}
|
||||
|
||||
// PORT: AVA2 ENABLE_GRAPHIC_ON_OFF effect level, applied to attached effects (skills, buffs, refine glow).
|
||||
void CInstanceBase::__UpdateEffectShown()
|
||||
{
|
||||
const int iLevel = CPythonSystem::Instance().GetEffectLevel();
|
||||
bool isShown = true;
|
||||
if (iLevel == 4)
|
||||
isShown = false;
|
||||
else if (iLevel != 0 && !__IsMainInstance())
|
||||
{
|
||||
if (iLevel == 1)
|
||||
isShown = IsEnemy() || IsStone();
|
||||
else if (iLevel == 2)
|
||||
isShown = IsPC();
|
||||
else
|
||||
isShown = false;
|
||||
}
|
||||
m_GraphicThingInstance.SetAttachingEffectShown(isShown);
|
||||
}
|
||||
|
||||
bool CInstanceBase::__CanRender()
|
||||
{
|
||||
if (!__IsInViewFrustum())
|
||||
|
||||
@@ -407,6 +407,7 @@ class CInstanceBase
|
||||
protected:
|
||||
bool __IsExistMainInstance();
|
||||
bool __IsMainInstance();
|
||||
void __UpdateEffectShown();
|
||||
bool __MainCanSeeHiddenThing();
|
||||
float __GetBowRange();
|
||||
|
||||
|
||||
@@ -110,6 +110,9 @@ class CPythonSystem : public CSingleton<CPythonSystem>
|
||||
bool IsAlwaysShowName();
|
||||
bool IsShowDamage();
|
||||
bool IsShowSalesText();
|
||||
// PORT: AVA2 effect_level (0 all, 1 hide players/NPCs, 2 hide monsters/NPCs, 3 hide others, 4 hide all).
|
||||
int GetEffectLevel() { return m_iPortEffectLevel; }
|
||||
void SetEffectLevel(int iLevel) { m_iPortEffectLevel = iLevel < 0 || iLevel > 4 ? 0 : iLevel; }
|
||||
bool IsUseDefaultIME();
|
||||
bool IsNoSoundCard();
|
||||
bool IsAutoTiling();
|
||||
@@ -159,4 +162,5 @@ class CPythonSystem : public CSingleton<CPythonSystem>
|
||||
bool m_isInterfaceConfig;
|
||||
PyObject * m_poInterfaceHandler;
|
||||
TWindowStatus m_WindowStatus[WINDOW_MAX_NUM];
|
||||
int m_iPortEffectLevel = 0;
|
||||
};
|
||||
@@ -211,6 +211,22 @@ PyObject * systemSetShowSalesTextFlag(PyObject * poSelf, PyObject * poArgs)
|
||||
return Py_BuildNone();
|
||||
}
|
||||
|
||||
PyObject * systemSetEffectLevel(PyObject * poSelf, PyObject * poArgs)
|
||||
{
|
||||
int iLevel;
|
||||
if (!PyTuple_GetInteger(poArgs, 0, &iLevel))
|
||||
return Py_BuildException();
|
||||
|
||||
CPythonSystem::Instance().SetEffectLevel(iLevel);
|
||||
|
||||
return Py_BuildNone();
|
||||
}
|
||||
|
||||
PyObject * systemGetEffectLevel(PyObject * poSelf, PyObject * poArgs)
|
||||
{
|
||||
return Py_BuildValue("i", CPythonSystem::Instance().GetEffectLevel());
|
||||
}
|
||||
|
||||
PyObject * systemIsAlwaysShowName(PyObject * poSelf, PyObject * poArgs)
|
||||
{
|
||||
return Py_BuildValue("i", CPythonSystem::Instance().IsAlwaysShowName());
|
||||
@@ -422,6 +438,8 @@ void initsystem()
|
||||
|
||||
{ "SetShowSalesTextFlag", systemSetShowSalesTextFlag, METH_VARARGS },
|
||||
{ "IsShowSalesText", systemIsShowSalesText, METH_VARARGS },
|
||||
{ "SetEffectLevel", systemSetEffectLevel, METH_VARARGS }, // PORT: AVA2
|
||||
{ "GetEffectLevel", systemGetEffectLevel, METH_VARARGS },
|
||||
|
||||
{ "GetShadowLevel", systemGetShadowLevel, METH_VARARGS },
|
||||
{ "SetShadowLevel", systemSetShadowLevel, METH_VARARGS },
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import types
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[2]
|
||||
|
||||
def script(name):return (ROOT/'src/platform/ScriptLib'/name).read_text().split('R"PY(',1)[1].rsplit(')PY";',1)[0]
|
||||
|
||||
|
||||
class Widget(object):
|
||||
def __init__(self,*a,**k):self.shown=False;self.text='';self.pos=(0,0);self.size=(0,0)
|
||||
def __getattr__(self,name):return lambda *a,**k:None
|
||||
def Show(self):self.shown=True
|
||||
def Hide(self):self.shown=False
|
||||
def IsShow(self):return self.shown
|
||||
def SetText(self,text):self.text=text
|
||||
def SetPosition(self,x,y):self.pos=(x,y)
|
||||
def GetGlobalPosition(self):return self.pos
|
||||
def SetSize(self,w,h):self.size=(w,h)
|
||||
def GetWidth(self):return self.size[0]
|
||||
def GetHeight(self):return self.size[1]
|
||||
|
||||
|
||||
class Action(Widget):
|
||||
def __init__(self,parent,x,y,width,text,event):
|
||||
Widget.__init__(self);self.pos=(x,y);self.event=event;self.enabled=True;self.text=text;self.shown=True
|
||||
def SetEnabled(self,enabled):self.enabled=enabled
|
||||
|
||||
|
||||
class Stream(object):
|
||||
def __init__(self):
|
||||
self.id='admin';self.pwd='secret';self.addr='10.0.0.1';self.port=13000;self.account_addr='10.0.0.1';self.account_port=11000
|
||||
self.slot=2;self.isAutoSelect=0
|
||||
def SetConnectInfo(self,addr,port,account_addr=0,account_port=0):
|
||||
self.addr=addr;self.port=port;self.account_addr=account_addr;self.account_port=account_port
|
||||
def SetCharacterSlot(self,slot):self.slot=slot
|
||||
def GetCharacterSlot(self):return self.slot
|
||||
|
||||
|
||||
class Login(object):
|
||||
# introLogin.LoginWindow.Open resets the connect info and the slot from loginInfo.xml.
|
||||
def __init__(self,stream,log):self.stream=stream;self.log=log
|
||||
def Open(self):self.stream.SetConnectInfo('',0,'',0);self.stream.SetCharacterSlot(0);self.stream.isAutoSelect=0
|
||||
def OnUpdate(self):pass
|
||||
def OnLoginFailure(self,error):self.log.append(('failure',error))
|
||||
def OnConnectFailure(self):self.log.append(('connect',))
|
||||
def Connect(self,id,pwd):self.log.append(('connect_to',self.stream.addr,self.stream.port,id,pwd))
|
||||
|
||||
|
||||
class ChannelTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.time=1.;self.sent=[];self.chat=[];self.log=[];self.serverinfo=[]
|
||||
self.cwd=os.getcwd();self.tmp=tempfile.TemporaryDirectory();os.chdir(self.tmp.name)
|
||||
mods={n:types.ModuleType(n) for n in ('app','chat','game','grp','introLogin','net','serverInfo','ui','mt_biolog','mt_wiki')}
|
||||
mods['app'].GetTime=lambda:self.time
|
||||
mods['chat'].CHAT_TYPE_INFO=1;mods['chat'].AppendChat=lambda t,m:self.chat.append(m)
|
||||
mods['net'].SendChatPacket=self.sent.append;mods['net'].SetServerInfo=self.serverinfo.append
|
||||
mods['game'].GameWindow=type('GameWindow',(),dict(Open=lambda s:None,Close=lambda s:None,OnUpdate=lambda s:None))
|
||||
mods['introLogin'].LoginWindow=Login
|
||||
si=mods['serverInfo']
|
||||
si.REGION_DICT={0:{1:{'name':'Metin2','channel':{
|
||||
1:{'name':'CH1','ip':'10.0.0.1','tcp_port':13000},2:{'name':'CH2','ip':'10.0.0.1','tcp_port':13010},
|
||||
3:{'name':'CH3','ip':'10.0.0.1','tcp_port':13020}}},
|
||||
2:{'name':'Test','channel':{1:{'name':'CH1','ip':'127.0.0.1','tcp_port':13000}}}}}
|
||||
si.REGION_AUTH_SERVER_DICT={0:{1:{'ip':'10.0.0.1','port':11000},2:{'ip':'127.0.0.1','port':11000}}}
|
||||
grp=mods['grp'];grp.SetColor=grp.RenderBar=grp.RenderBox=lambda *a:None
|
||||
mods['ui'].Window=Widget
|
||||
mods['mt_biolog'].Action=Action;mods['mt_biolog'].Text=lambda p,x,y,t='',c=0:Widget();mods['mt_biolog'].L=lambda t:t if isinstance(t,str) else t.decode('utf-8')
|
||||
mods['mt_wiki'].B=lambda t,limit=0:t
|
||||
self.previous={n:sys.modules.get(n) for n in mods}
|
||||
sys.modules.update(mods)
|
||||
self.ns={'__name__':'mt_channel'};exec(script('ChannelScript.inc'),self.ns)
|
||||
self.stream=Stream();self.game=sys.modules['game'];self.gw=self.game.GameWindow()
|
||||
self.gw.stream=self.stream;self.gw.interface=types.SimpleNamespace(wndMiniMap=Widget())
|
||||
|
||||
def tearDown(self):
|
||||
os.chdir(self.cwd);self.tmp.cleanup()
|
||||
for name,value in self.previous.items():
|
||||
if value is None:sys.modules.pop(name,None)
|
||||
else:sys.modules[name]=value
|
||||
|
||||
def test_locate(self):
|
||||
Locate=self.ns['Locate']
|
||||
self.assertEqual(Locate('10.0.0.1',13010),(0,1,2))
|
||||
self.assertEqual(Locate('127.0.0.1',13000),(0,2,1))
|
||||
self.assertEqual(Locate('10.0.0.1',13040),(0,1,0)) # unknown port: first server, current unknown
|
||||
Path('channel.inf').write_text('2 1 0')
|
||||
self.assertEqual(Locate('10.0.0.1',13040),(0,2,0)) # the server last picked on the login board
|
||||
Path('channel.inf').write_text('9 1 0');self.assertEqual(Locate('x',1),(0,1,0))
|
||||
|
||||
def test_full_switch(self):
|
||||
game=self.game;gw=self.gw
|
||||
game.GameWindow.Open(gw);w=self.ns['g_window'];self.assertEqual(self.ns['g_entry'].pos,(4,304))
|
||||
w.Open();self.assertEqual(len(w.channelButtons),3);self.assertIn('CH1',w.current.text)
|
||||
self.assertFalse(w.channelButtons[0].enabled);self.assertIn('【',w.channelButtons[0].text)
|
||||
w.channelButtons[1].event();self.assertEqual(self.sent,['/logout'])
|
||||
self.assertTrue(all(not b.enabled for b in w.channelButtons));self.assertIn('正在退出',w.status.text)
|
||||
w.channelButtons[2].event();self.assertEqual(self.sent,['/logout']) # busy: a second /logout would cancel it
|
||||
game.GameWindow.Close(gw) # server closed the session -> SetLoginPhase
|
||||
login=sys.modules['introLogin'].LoginWindow(self.stream,self.log);login.Open()
|
||||
self.assertEqual(self.log,[('connect_to','10.0.0.1',13010,'admin','secret')])
|
||||
self.assertEqual((self.stream.account_addr,self.stream.account_port,self.stream.slot,self.stream.isAutoSelect),('10.0.0.1',11000,2,1))
|
||||
self.assertEqual(self.serverinfo,['Metin2, CH2']);self.assertEqual(Path('channel.inf').read_text(),'1 2 0')
|
||||
game.GameWindow.Open(gw) # introSelect auto-selected slot 2 and the game started
|
||||
self.assertEqual(self.stream.isAutoSelect,0);self.assertIsNone(self.ns['g_switcher'].stage)
|
||||
self.assertIn('已换到 CH2',self.chat[-1])
|
||||
w=self.ns['g_window'];w.Open();self.assertIn('CH2',w.current.text);self.assertTrue(w.channelButtons[0].enabled)
|
||||
login.Open();self.assertEqual(len(self.log),1) # a later login window is left alone
|
||||
|
||||
def test_logout_refused_times_out(self):
|
||||
self.game.GameWindow.Open(self.gw);w=self.ns['g_window'];w.Open();w.channelButtons[2].event()
|
||||
self.time+=19;self.game.GameWindow.OnUpdate(self.gw);self.assertEqual(self.ns['g_switcher'].stage,'logout')
|
||||
self.time+=1;self.game.GameWindow.OnUpdate(self.gw);self.assertIsNone(self.ns['g_switcher'].stage)
|
||||
self.assertIn('换线已取消',self.chat[-1]);self.assertTrue(w.channelButtons[2].enabled)
|
||||
|
||||
def test_login_failure_clears_auto_select(self):
|
||||
self.game.GameWindow.Open(self.gw);w=self.ns['g_window'];w.Open();w.channelButtons[1].event()
|
||||
login=sys.modules['introLogin'].LoginWindow(self.stream,self.log);login.Open()
|
||||
self.assertEqual(self.stream.isAutoSelect,1)
|
||||
login.OnLoginFailure('ALREADY');self.assertEqual(self.stream.isAutoSelect,0)
|
||||
self.assertEqual(self.log[-1],('failure','ALREADY'));self.assertIn('登录目标频道失败',self.chat[-1])
|
||||
self.assertIsNone(self.ns['g_switcher'].stage)
|
||||
|
||||
def test_refuses_without_account_or_same_channel(self):
|
||||
s=self.ns['g_switcher'];place=(0,1,1)
|
||||
self.assertFalse(s.Start(self.stream,place,1));self.assertEqual(s.error,'channel')
|
||||
self.assertFalse(s.Start(self.stream,place,7));self.assertEqual(s.error,'channel')
|
||||
self.stream.pwd='';self.assertFalse(s.Start(self.stream,place,2));self.assertEqual(s.error,'account')
|
||||
self.assertEqual(self.sent,[])
|
||||
|
||||
def test_server_logout_countdown_fits_timeout(self):
|
||||
server=ROOT.parent/'metin2-server/src/server/game/src/cmd_general.cpp'
|
||||
if not server.exists():self.skipTest('server checkout not installed')
|
||||
text=server.read_text(encoding='latin1');body=text.split('ACMD(do_cmd)',1)[1].split('\n}\n',1)[0]
|
||||
self.assertIn('info->left_second = 10;',body);self.assertLess(10+2,self.ns['LOGOUT_TIMEOUT'])
|
||||
self.assertIn('event_cancel(&ch->m_pkTimedEvent)',body) # why the switcher never sends /logout twice
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,94 @@
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
import types
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[2]
|
||||
|
||||
def script(name):return (ROOT/'src/platform/ScriptLib'/name).read_text().split('R"PY(',1)[1].rsplit(')PY";',1)[0]
|
||||
|
||||
|
||||
class Widget(object):
|
||||
def __init__(self,*a,**k):self.shown=False;self.text='';self.pos=(0,0);self.size=(0,0)
|
||||
def __getattr__(self,name):return lambda *a,**k:None
|
||||
def Show(self):self.shown=True
|
||||
def Hide(self):self.shown=False
|
||||
def IsShow(self):return self.shown
|
||||
def SetText(self,text):self.text=text
|
||||
def SetPosition(self,x,y):self.pos=(x,y)
|
||||
def GetGlobalPosition(self):return self.pos
|
||||
def SetSize(self,w,h):self.size=(w,h)
|
||||
def GetWidth(self):return self.size[0]
|
||||
def GetHeight(self):return self.size[1]
|
||||
|
||||
|
||||
class Action(Widget):
|
||||
def __init__(self,parent,x,y,width,text,event):
|
||||
Widget.__init__(self);self.pos=(x,y);self.event=event;self.text=text;self.shown=True
|
||||
|
||||
|
||||
class DisplayTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.cwd=os.getcwd();self.tmp=tempfile.TemporaryDirectory();os.chdir(self.tmp.name)
|
||||
self.state=dict(effect=None,name=True,damage=True,parts={});self.opened=[]
|
||||
mods={n:types.ModuleType(n) for n in ('background','game','grp','systemSetting','ui','mt_biolog','mt_wiki')}
|
||||
bg=mods['background'];bg.PART_TREE=3;bg.PART_CLOUD=2;bg.SetVisiblePart=lambda part,on:self.state['parts'].__setitem__(part,on)
|
||||
ss=mods['systemSetting'];ss.SetEffectLevel=lambda v:self.state.__setitem__('effect',v)
|
||||
ss.IsAlwaysShowName=lambda:self.state['name'];ss.SetAlwaysShowNameFlag=lambda v:self.state.__setitem__('name',bool(v))
|
||||
ss.IsShowDamage=lambda:self.state['damage'];ss.SetShowDamageFlag=lambda v:self.state.__setitem__('damage',bool(v))
|
||||
mods['game'].GameWindow=type('GameWindow',(),dict(Open=lambda s:self.opened.append(1),Close=lambda s:None))
|
||||
grp=mods['grp'];grp.SetColor=grp.RenderBar=grp.RenderBox=lambda *a:None
|
||||
mods['ui'].Window=Widget
|
||||
mods['mt_biolog'].Action=Action;mods['mt_biolog'].Text=lambda p,x,y,t='',c=0:Widget();mods['mt_biolog'].L=lambda t:t if isinstance(t,str) else t.decode('utf-8')
|
||||
mods['mt_wiki'].B=lambda t,limit=0:t
|
||||
self.previous={n:sys.modules.get(n) for n in mods}
|
||||
sys.modules.update(mods)
|
||||
|
||||
def load(self):
|
||||
self.ns={'__name__':'mt_display'};exec(script('DisplayScript.inc'),self.ns);return self.ns
|
||||
|
||||
def tearDown(self):
|
||||
os.chdir(self.cwd);self.tmp.cleanup()
|
||||
for name,value in self.previous.items():
|
||||
if value is None:sys.modules.pop(name,None)
|
||||
else:sys.modules[name]=value
|
||||
|
||||
def test_defaults_and_config(self):
|
||||
ns=self.load();self.assertEqual(self.state['effect'],0)
|
||||
o=ns['Options']();self.assertEqual(o.Dump(),'0 1 1')
|
||||
for bad in ('5 1 1','1 2 1','a 1 1','1 1','10 1 1','-1 1 1'):
|
||||
o=ns['Options']();o.Load(bad);self.assertEqual(o.Dump(),'0 1 1')
|
||||
Path('mt_display.cfg').write_text('3 0 1')
|
||||
self.load();self.assertEqual(self.state['effect'],3) # applied at boot, before any map
|
||||
|
||||
def test_game_window_applies_and_saves(self):
|
||||
Path('mt_display.cfg').write_text('2 0 1')
|
||||
ns=self.load();game=sys.modules['game'];gw=game.GameWindow();gw.interface=types.SimpleNamespace(wndMiniMap=Widget())
|
||||
game.GameWindow.Open(gw);self.assertEqual(self.opened,[1])
|
||||
self.assertEqual(self.state['parts'],{3:0,2:1});self.assertEqual(ns['g_entry'].pos,(4,252))
|
||||
w=ns['g_window'];w.Open()
|
||||
self.assertIn('【',w.levelButtons[2].text);self.assertNotIn('【',w.levelButtons[0].text)
|
||||
self.assertNotIn('【',w.treeButton.text);self.assertIn('【',w.cloudButton.text)
|
||||
w.levelButtons[4].event();self.assertEqual(self.state['effect'],4)
|
||||
w.ToggleTree();w.ToggleCloud();self.assertEqual(self.state['parts'],{3:1,2:0})
|
||||
self.assertEqual(Path('mt_display.cfg').read_text(),'4 1 0')
|
||||
w.ToggleName();w.ToggleDamage();self.assertEqual((self.state['name'],self.state['damage']),(False,False))
|
||||
self.assertNotIn('【',w.nameButton.text)
|
||||
game.GameWindow.Close(gw);self.assertIsNone(ns['g_window']);self.assertIsNone(ns['g_entry'])
|
||||
|
||||
def test_levels_match_native_rule(self):
|
||||
ns=self.load();text=(ROOT/'src/port/UserInterface/InstanceBase.cpp').read_text(encoding='latin1')
|
||||
body=text.split('void CInstanceBase::__UpdateEffectShown()',1)[1].split('\n}\n',1)[0]
|
||||
self.assertEqual(len(ns['LEVELS']),5);self.assertIn('iLevel == 4',body)
|
||||
self.assertIn('IsEnemy() || IsStone()',body);self.assertIn('IsPC()',body)
|
||||
system=(ROOT/'src/port/UserInterface/PythonSystem.h').read_text(encoding='latin1')
|
||||
self.assertIn('iLevel > 4',system)
|
||||
render=(ROOT/'src/port/GameLib/MapOutdoorRender.cpp').read_text(encoding='latin1')
|
||||
blocker=render.split('void CMapOutdoor::RenderPCBlocker()',1)[1].split('\n}\n',1)[0]
|
||||
self.assertIn('TREE_OBJECT != pInstance->GetType()',blocker) # near trees are drawn as PC blockers
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,127 @@
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
import types
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[2]
|
||||
|
||||
def script(name):return (ROOT/'src/platform/ScriptLib'/name).read_text().split('R"PY(',1)[1].rsplit(')PY";',1)[0]
|
||||
|
||||
|
||||
class Widget(object):
|
||||
def __init__(self,*a,**k):self.shown=False;self.text='';self.pos=(0,0);self.size=(0,0)
|
||||
def __getattr__(self,name):return lambda *a,**k:None
|
||||
def Show(self):self.shown=True
|
||||
def Hide(self):self.shown=False
|
||||
def IsShow(self):return self.shown
|
||||
def SetText(self,text):self.text=text
|
||||
def SetPosition(self,x,y):self.pos=(x,y)
|
||||
def GetGlobalPosition(self):return self.pos
|
||||
def SetSize(self,w,h):self.size=(w,h)
|
||||
def GetWidth(self):return self.size[0]
|
||||
def GetHeight(self):return self.size[1]
|
||||
|
||||
|
||||
class Action(Widget):
|
||||
def __init__(self,parent,x,y,width,text,event):
|
||||
Widget.__init__(self);self.pos=(x,y);self.event=event;self.enabled=True;self.text=text;self.shown=True
|
||||
def SetEnabled(self,enabled):self.enabled=enabled
|
||||
|
||||
|
||||
class PickupTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.time=1.;self.sent=[];self.chat=[];self.events=[];self.single=[]
|
||||
self.cwd=os.getcwd();self.tmp=tempfile.TemporaryDirectory();os.chdir(self.tmp.name)
|
||||
mods={n:types.ModuleType(n) for n in ('app','chat','game','grp','net','ui','mt_biolog','mt_wiki')}
|
||||
mods['app'].GetTime=lambda:self.time
|
||||
mods['chat'].CHAT_TYPE_INFO=1;mods['chat'].AppendChat=lambda t,m:self.chat.append(m)
|
||||
mods['net'].SendChatPacket=self.sent.append
|
||||
mods['game'].GameWindow=type('GameWindow',(),dict(Open=lambda s:None,Close=lambda s:None,
|
||||
BINARY_ServerCommand_Run=lambda s,line:7,PickUpItem=lambda s:self.single.append(1)))
|
||||
grp=mods['grp'];grp.SetColor=grp.RenderBar=grp.RenderBox=lambda *a:None
|
||||
mods['ui'].Window=Widget
|
||||
mods['mt_biolog'].Action=Action;mods['mt_biolog'].Text=lambda p,x,y,t='',c=0:Widget();mods['mt_biolog'].L=lambda t:t if isinstance(t,str) else t.decode('utf-8')
|
||||
mods['mt_wiki'].B=lambda t,limit=0:t
|
||||
self.previous={n:sys.modules.get(n) for n in mods}
|
||||
sys.modules.update(mods)
|
||||
self.load()
|
||||
|
||||
def load(self):
|
||||
self.ns={'__name__':'mt_pickup'};exec(script('PickupScript.inc'),self.ns)
|
||||
self.picker=self.ns['Picker'](self.sent.append,lambda:self.time,self.events.append)
|
||||
|
||||
def tearDown(self):
|
||||
os.chdir(self.cwd);self.tmp.cleanup()
|
||||
for name,value in self.previous.items():
|
||||
if value is None:sys.modules.pop(name,None)
|
||||
else:sys.modules[name]=value
|
||||
|
||||
def test_press_sends_once_per_gap_and_waits_for_reply(self):
|
||||
self.assertTrue(self.picker.Press());self.assertTrue(self.picker.Press())
|
||||
self.assertEqual(self.sent,['/mt_pickup 1 255'])
|
||||
self.time+=.6;self.picker.Press();self.assertEqual(len(self.sent),1) # still waiting for the reply
|
||||
self.assertTrue(self.picker.Receive('MTPU1 done 5 4 1'))
|
||||
self.assertEqual(self.picker.result,dict(found=5,picked=4,failed=1))
|
||||
self.picker.Press();self.assertEqual(len(self.sent),2)
|
||||
self.picker.Receive('MTPU1 done 0 0 0');self.time+=.1;self.picker.Press()
|
||||
self.assertEqual(len(self.sent),2) # inside the 0.5 s gap: swallowed (key repeat)
|
||||
|
||||
def test_errors_malformed_and_foreign_lines(self):
|
||||
self.picker.Press();self.picker.Receive('MTPU1 error busy')
|
||||
self.assertEqual(self.picker.error,'busy');self.assertIsNone(self.picker.waiting)
|
||||
for bad in ('MTPU1 done 1 2','MTPU1 done a 1 1','MTPU1 error boom','MTPU1 done 1 1 1 1'):
|
||||
self.assertTrue(self.picker.Receive(bad))
|
||||
self.assertEqual(self.picker.error,'busy')
|
||||
self.assertFalse(self.picker.Receive('MTSB1 state 0 0 0 0 0 0 0 idle'))
|
||||
|
||||
def test_timeout_falls_back_to_single_pickup(self):
|
||||
self.picker.Press();self.time+=3.1
|
||||
self.assertFalse(self.picker.Press());self.assertTrue(self.picker.unsupported)
|
||||
self.assertEqual(self.events,['unsupported']);self.assertEqual(len(self.sent),1)
|
||||
self.picker.Receive('MTPU1 done 0 0 0');self.assertFalse(self.picker.unsupported) # a late reply re-enables
|
||||
|
||||
def test_disabled_and_category_mask(self):
|
||||
self.picker.enabled=False;self.assertFalse(self.picker.Press());self.assertEqual(self.sent,[])
|
||||
self.picker.enabled=True;self.picker.mask=1
|
||||
self.picker.Toggle(1);self.assertEqual(self.picker.mask,1) # the last category stays on
|
||||
self.picker.Toggle(32);self.picker.Press();self.assertEqual(self.sent,['/mt_pickup 1 33'])
|
||||
|
||||
def test_config_round_trip_and_bad_files(self):
|
||||
self.picker.enabled=False;self.picker.mask=6;self.ns['SaveConfig'](self.picker)
|
||||
other=self.ns['Picker'](None,None);self.ns['LoadConfig'](other)
|
||||
self.assertEqual((other.enabled,other.mask),(False,6))
|
||||
for text in ('1 0','1 256','2 5','x 5','1','1 -3'):
|
||||
p=self.ns['Picker'](None,None);p.Load(text);self.assertEqual((p.enabled,p.mask),(True,255))
|
||||
|
||||
def test_game_window_hooks(self):
|
||||
game=sys.modules['game'];gw=game.GameWindow();gw.interface=types.SimpleNamespace(wndMiniMap=Widget())
|
||||
game.GameWindow.Open(gw);w=self.ns['g_window'];picker=self.ns['g_picker']
|
||||
self.assertEqual(self.ns['g_entry'].pos,(4,200))
|
||||
game.GameWindow.PickUpItem(gw);self.assertEqual(self.sent,['/mt_pickup 1 255']);self.assertEqual(self.single,[])
|
||||
self.assertEqual(game.GameWindow.BINARY_ServerCommand_Run(gw,'MTPU1 done 3 3 0'),1)
|
||||
self.assertEqual(game.GameWindow.BINARY_ServerCommand_Run(gw,'other'),7)
|
||||
self.assertIn('拾取 3 件',w.status.text if hasattr(w.status,'text') else '')
|
||||
w.Open();w.ToggleCategory(128);self.assertNotIn('【',w.categoryButtons[7].text);self.assertIn('【',w.categoryButtons[0].text)
|
||||
w.ToggleEnabled();self.assertFalse(picker.enabled);self.assertFalse(w.categoryButtons[0].enabled)
|
||||
game.GameWindow.PickUpItem(gw);self.assertEqual(self.single,[1])
|
||||
self.assertEqual(Path('mt_pickup.cfg').read_text(),'0 127')
|
||||
self.time+=1;w.ToggleEnabled();game.GameWindow.PickUpItem(gw);self.time+=3.1;w.OnUpdate()
|
||||
self.assertTrue(picker.unsupported);self.assertIn('单个拾取',self.chat[-1])
|
||||
game.GameWindow.PickUpItem(gw);self.assertEqual(self.single,[1,1])
|
||||
game.GameWindow.Close(gw);self.assertIsNone(self.ns['g_window']);self.assertIsNone(self.ns['g_entry'])
|
||||
|
||||
def test_server_constants_match(self):
|
||||
server=ROOT.parent/'metin2-server/src/server/game/src/port_pickup.h'
|
||||
if not server.exists():self.skipTest('server checkout not installed')
|
||||
text=server.read_text(encoding='latin1')
|
||||
bits=dict((name,int(v)) for name,v in re.findall(r'PORT_PICKUP_([A-Z]+)=(\d+)',text))
|
||||
self.assertEqual(bits.pop('ALL'),self.ns['ALL'])
|
||||
self.assertEqual(sorted(bits.values()),[bit for bit,name in self.ns['CATEGORIES']])
|
||||
self.assertTrue(set(re.findall(r'MTPU1 error ([a-z_]+)"',text))<=set(self.ns['ERRORS']))
|
||||
self.assertIn('kPortPickupGapMs=500',text);self.assertEqual(self.ns['SEND_GAP'],.5)
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
@@ -0,0 +1,154 @@
|
||||
import re
|
||||
import sys
|
||||
import types
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[2]
|
||||
|
||||
def script(name):return (ROOT/'src/platform/ScriptLib'/name).read_text().split('R"PY(',1)[1].rsplit(')PY";',1)[0]
|
||||
|
||||
|
||||
class Widget(object):
|
||||
def __init__(self,*a,**k):self.shown=False;self.text='';self.pos=(0,0);self.size=(0,0)
|
||||
def __getattr__(self,name):return lambda *a,**k:None
|
||||
def Show(self):self.shown=True
|
||||
def Hide(self):self.shown=False
|
||||
def IsShow(self):return self.shown
|
||||
def SetText(self,text):self.text=text
|
||||
def SetPosition(self,x,y):self.pos=(x,y)
|
||||
def GetLocalPosition(self):return self.pos
|
||||
def GetGlobalPosition(self):return self.pos
|
||||
def SetSize(self,w,h):self.size=(w,h)
|
||||
def GetWidth(self):return self.size[0]
|
||||
def GetHeight(self):return self.size[1]
|
||||
|
||||
|
||||
class Action(Widget):
|
||||
def __init__(self,parent,x,y,width,text,event):
|
||||
Widget.__init__(self);self.pos=(x,y);self.event=event;self.enabled=True;self.label=Widget();self.text=text;self.shown=True
|
||||
def SetEnabled(self,enabled):self.enabled=enabled
|
||||
|
||||
|
||||
class SwitchbotTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.time=1.;self.sent=[];self.chat=[];self.events=[]
|
||||
self.inventory={10:(11209,1,[(3,2),(15,1)]),20:(71084,7,[]),21:(71084,3,[]),30:(27001,5,[])}
|
||||
protos={11209:(2,0),71084:(3,18),27001:(3,0)}
|
||||
mods={n:types.ModuleType(n) for n in ('app','chat','game','grp','item','net','player','ui','uiToolTip','wndMgr','mt_biolog','mt_wiki')}
|
||||
mods['app'].GetTime=lambda:self.time
|
||||
mods['chat'].CHAT_TYPE_INFO=1;mods['chat'].AppendChat=lambda t,m:self.chat.append(m)
|
||||
mods['net'].SendChatPacket=self.sent.append
|
||||
mods['game'].GameWindow=type('GameWindow',(),dict(Open=lambda s:None,Close=lambda s:None,BINARY_ServerCommand_Run=lambda s,line:7))
|
||||
grp=mods['grp'];grp.SetColor=grp.RenderBar=grp.RenderBox=lambda *a:None
|
||||
it=mods['item'];it.ITEM_TYPE_WEAPON=1;it.ITEM_TYPE_ARMOR=2;it.ITEM_TYPE_USE=3;self.selected=None
|
||||
it.SelectItem=lambda v:setattr(self,'selected',v);it.GetItemType=lambda:protos[self.selected][0];it.GetItemSubType=lambda:protos[self.selected][1]
|
||||
it.GetItemName=lambda:'N%d'%self.selected
|
||||
pl=mods['player'];pl.INVENTORY=1;pl.INVENTORY_PAGE_SIZE=45;pl.INVENTORY_PAGE_COUNT=5
|
||||
pl.GetItemIndex=lambda w,c:self.inventory.get(c,(0,))[0];pl.GetItemCount=lambda w,c:self.inventory[c][1]
|
||||
pl.GetItemAttribute=lambda w,c,i:(self.inventory[c][2]+[(0,0)]*5)[i]
|
||||
mods['ui'].Window=Widget
|
||||
mods['uiToolTip'].ItemToolTip=type('ItemToolTip',(),dict(AFFECT_DICT={3:lambda v:'STR+%d'%v}))
|
||||
mods['wndMgr'].GetScreenWidth=lambda:800;mods['wndMgr'].GetScreenHeight=lambda:600
|
||||
mods['mt_biolog'].Action=Action;mods['mt_biolog'].Text=lambda p,x,y,t='',c=0:Widget();mods['mt_biolog'].L=lambda t:t if isinstance(t,str) else t.decode('utf-8')
|
||||
mods['mt_wiki'].U=lambda t:t if isinstance(t,str) else t.decode('utf-8');mods['mt_wiki'].B=lambda t,limit=0:t
|
||||
self.previous={n:sys.modules.get(n) for n in mods}
|
||||
sys.modules.update(mods)
|
||||
self.ns={'__name__':'mt_switchbot'};exec(script('SwitchbotScript.inc'),self.ns)
|
||||
self.bot=self.ns['Bot'](self.sent.append,lambda:self.time,self.events.append)
|
||||
|
||||
def tearDown(self):
|
||||
for name,value in self.previous.items():
|
||||
if value is None:sys.modules.pop(name,None)
|
||||
else:sys.modules[name]=value
|
||||
|
||||
def advance(self,seconds=.4):self.time+=seconds;self.bot.Tick()
|
||||
|
||||
def load(self,bot,cell=10):
|
||||
for line in ('MTSB1 attrs %d 11209 3'%cell,'MTSB1 attr 0 3 12','MTSB1 attr 1 63 6','MTSB1 attr 2 71 30','MTSB1 attrs_end %d 3'%cell):bot.Receive(line)
|
||||
|
||||
def test_commands_are_paced_and_attrs_requests_collapse(self):
|
||||
self.bot.RequestAttrs(10);self.bot.RequestAttrs(11);self.bot.RequestAttrs(12);self.bot.Status()
|
||||
self.assertEqual(self.sent,['/mt_switchbot 1 attrs 10'])
|
||||
self.load(self.bot);self.advance()
|
||||
self.assertEqual(self.sent[-1],'/mt_switchbot 1 attrs 12')
|
||||
self.bot.Receive('MTSB1 error attrs no_attr');self.advance()
|
||||
self.assertEqual(self.sent[-1],'/mt_switchbot 1 status')
|
||||
self.assertEqual(len(self.sent),3)
|
||||
|
||||
def test_atomic_attr_list_and_rejected_partials(self):
|
||||
self.load(self.bot)
|
||||
self.assertEqual(self.bot.allowed[10]['rows'],[(3,12),(63,6),(71,30)])
|
||||
for bad in (['MTSB1 attrs 11 1 2','MTSB1 attr 0 3 12','MTSB1 attrs_end 11 2'],
|
||||
['MTSB1 attrs 11 1 1','MTSB1 attr 1 3 12','MTSB1 attrs_end 11 1'],
|
||||
['MTSB1 attrs 11 1 1','MTSB1 attr 0 3 -1','MTSB1 attrs_end 11 1'],
|
||||
['MTSB1 attrs_end 11 0']):
|
||||
for line in bad:self.assertTrue(self.bot.Receive(line))
|
||||
self.assertNotIn(11,self.bot.allowed)
|
||||
self.assertFalse(self.bot.Receive('MTF1 cap 1 1 127 0'))
|
||||
|
||||
def test_start_validates_against_server_list_and_builds_command(self):
|
||||
self.load(self.bot)
|
||||
self.assertEqual(self.bot.Start(10,71084,100,[[(3,13)],[]]),'target')
|
||||
self.assertEqual(self.bot.Start(10,71084,100,[[(1,1)],[]]),'target')
|
||||
self.assertEqual(self.bot.Start(10,71084,100,[[(3,1),(3,2)],[]]),'invalid')
|
||||
self.assertEqual(self.bot.Start(10,71084,1001,[[(3,1)],[]]),'invalid')
|
||||
self.assertEqual(self.bot.Start(10,71084,100,[[],[]]),'invalid')
|
||||
self.assertIsNone(self.bot.Start(10,71084,100,[[(3,8),(63,6)],[(71,30)]]))
|
||||
self.advance()
|
||||
self.assertEqual(self.sent[-1],'/mt_switchbot 1 start 10 71084 100 2 3 8 63 6 1 71 30')
|
||||
self.bot.Receive('MTSB1 error start running')
|
||||
self.assertIsNone(self.bot.Start(10,71084,5,[[],[(71,1)]]));self.advance()
|
||||
self.assertEqual(self.sent[-1],'/mt_switchbot 1 start 10 71084 5 1 71 1') # empty first alternative skipped
|
||||
|
||||
def test_state_errors_and_timeout(self):
|
||||
self.bot.Receive('MTSB1 state 1 10 11209 3 100 71084 4 running')
|
||||
self.assertTrue(self.bot.Running());self.assertEqual(self.bot.state['scrolls'],4)
|
||||
self.bot.Receive('MTSB1 state 0 10 11209 4 100 71084 3 matched')
|
||||
self.assertFalse(self.bot.Running());self.assertEqual(self.bot.state['reason'],'matched')
|
||||
self.bot.Receive('MTSB1 state 0 10 11209 4 100 71084 3 exploded')
|
||||
self.assertEqual(self.bot.state['reason'],'matched') # unknown reason ignored
|
||||
self.bot.Receive('MTSB1 error start busy');self.assertEqual(self.bot.error,'busy')
|
||||
self.bot.Status();self.advance(4.1);self.advance()
|
||||
self.assertEqual(self.bot.error,'unsupported');self.assertTrue(self.bot.unsupported)
|
||||
|
||||
def test_server_constants_match(self):
|
||||
server=ROOT.parent/'metin2-server/src/server/game/src/port_switchbot.h'
|
||||
if not server.exists():self.skipTest('server checkout not installed')
|
||||
text=server.read_text(encoding='latin1')
|
||||
reasons=set(re.findall(r'return "([a-z_]+)"',text))|{'running','stopped','idle'}
|
||||
errors=set(re.findall(r'error [a-z%]+ ([a-z_]+)"',text))|{'invalid','rate'}
|
||||
self.assertTrue(reasons-{'invalid','running','item','equipped','no_attr','scroll','target','busy'}<=set(self.ns['REASONS']))
|
||||
self.assertTrue(errors<=set(self.ns['ERRORS']))
|
||||
self.assertIn('kPortSwitchLimit=1000',text);self.assertEqual(max(self.ns['LIMITS']),1000)
|
||||
self.assertEqual(self.ns['MAX_TARGETS'],5)
|
||||
|
||||
def test_window_scan_pick_start_and_notify(self):
|
||||
game=sys.modules['game'];window_type=game.GameWindow
|
||||
gw=window_type();gw.interface=types.SimpleNamespace(wndMiniMap=Widget())
|
||||
game.GameWindow.Open(gw);w=self.ns['g_window'];w.Open()
|
||||
self.assertEqual(w.items,[(10,11209)]);self.assertEqual(w.scrolls,[(71084,10)])
|
||||
self.assertEqual(self.sent,['/mt_switchbot 1 attrs 10']) # the status request waits for this reply
|
||||
self.load(w.bot);self.time+=.5;w.OnUpdate()
|
||||
self.assertEqual(self.sent[-1],'/mt_switchbot 1 status')
|
||||
self.assertEqual(game.GameWindow.BINARY_ServerCommand_Run(gw,'MTSB1 state 0 0 0 0 0 0 0 idle'),1)
|
||||
self.assertEqual(game.GameWindow.BINARY_ServerCommand_Run(gw,'other'),7)
|
||||
w.TogglePick();w.Pick(0)
|
||||
self.assertEqual(w.alternatives[0],[[3,12]])
|
||||
w.Adjust(0,-1);self.assertEqual(w.alternatives[0][0][1],10);w.Adjust(0,1);w.Adjust(0,1);self.assertEqual(w.alternatives[0][0][1],12)
|
||||
w.Start();self.time+=.5;w.OnUpdate()
|
||||
self.assertEqual(self.sent[-1],'/mt_switchbot 1 start 10 71084 100 1 3 12')
|
||||
w.bot.Receive('MTSB1 state 1 10 11209 1 100 71084 9 running');self.assertFalse(w.startButton.enabled)
|
||||
self.inventory[40]=self.inventory.pop(10);sent=len(self.sent) # moved while running: follow the server's cell
|
||||
w.bot.Receive('MTSB1 state 1 40 11209 2 100 71084 8 running');w.Scan()
|
||||
self.assertEqual(w.Selected(),(40,11209));self.assertEqual(w.alternatives[0],[[3,12]])
|
||||
self.assertEqual(w.Allowed(),[(3,12),(63,6),(71,30)]);self.time+=.5;w.OnUpdate();self.assertEqual(len(self.sent),sent)
|
||||
w.bot.Receive('MTSB1 state 0 40 11209 2 100 71084 8 stopped')
|
||||
self.inventory[5]=self.inventory.pop(40);w.Scan();self.assertEqual(w.Selected(),(5,11209)) # moved while idle: same vnum
|
||||
self.inventory[10]=self.inventory.pop(5);w.Scan()
|
||||
w.Hide();w.bot.Receive('MTSB1 state 0 10 11209 2 100 71084 8 matched')
|
||||
self.assertTrue(w.IsShow());self.assertIn('已获得目标属性',self.chat[-1])
|
||||
game.GameWindow.Close(gw);self.assertIsNone(self.ns['g_window'])
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
Reference in New Issue
Block a user