4 Commits
Author SHA1 Message Date
shenleiandClaude Opus 5.5 b8363693f1 Add batch gift box opening window (mt_chest)
Ctrl + right click on an ITEM_GIFTBOX opens a count window (1/10/50/all,
max 200) that sends /mt_chest and sums the MTCH1 gains into chat. Without
Ctrl or against a server without the command the original use runs.
Exports item.ITEM_TYPE_GIFTBOX. Verified live on the 203 channel5 core.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 23:31:03 +09:00
shenleiandClaude Opus 5.5 10f8c9760e Record the attribute lock production deploy
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 23:11:31 +09:00
shenleiandClaude Opus 5.5 a22c064587 Add attribute lock buttons to the switchbot window
Five per-slot toggles next to start/stop, shown only when the server
sends the MTSB1 lock line; locked attributes are marked in the current
attribute line. Server side: metin2-server docs/FEATURE-ATTR-LOCK.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 23:06:00 +09:00
shenleiandClaude Opus 5.5 ffe097ec57 Add world boss window (AVA2 uitrack world-boss tab, read-only)
mt_boss lists the server's timed boss regens from the MTF1 "bosses"
query: alive/max, countdown, map-local position and period, paged by 8,
with per-boss spawn reminders that only fire on a fresh alive snapshot.
Teleport is left out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 22:36:04 +09:00
15 changed files with 961 additions and 18 deletions
+64
View File
@@ -0,0 +1,64 @@
# AVA2 世界 Boss 追踪进度(v1)
2026-10-15。参考 AVA2 `uitrack` 的世界 Boss 页,只读。服务端见 metin2-server `docs/FEATURE-BOSS-TRACK.md`。没有移植 AVA2 的传送按钮(它会改变游戏进程);副本页已经由 `mt_dungeons` 实现。
## 与 AVA2 的差异
| 项目 | AVA2 | 本实现 |
| --- | --- | --- |
| 数据来源 | 专用封包 | 原有 `/mt_features` 查询,种类 `bosses`(能力位 256) |
| 跨核心 | 不明(AVA2 服务端源码不在本机) | 每个核心用原 `HEADER_GG_RELAY` 广播自己的 Boss 刷新点,旧核心会忽略 |
| 传送 | 有 | 无 |
| 提醒 | 有 | 有:刷新后在聊天框提示,以服务器快照为准 |
## 窗口
- 入口:小地图左侧按钮列中的“Boss”(换线按钮下方)。
- 标题“世界Boss”,有“刷新”“上一页/下一页”按钮,每页 8 行。
- 每行显示:
- `[CHn]` 或 `[共享]`(频道 99)、Boss 名、地图名;
- 状态(存活 a/m、刷新倒计时、即将刷新、不再刷新)、坐标(地图内坐标 /100,`ANYWHERE` 显示“随机位置”)、刷新周期;
- “提醒:开/关”按钮,只能对未存活、有计时的 Boss 打开。
- 窗口打开时每 30 秒刷新一次。倒计时按服务器时间和本地经过时间计算。
- 名称:
- Boss 名取自 `nonplayer.GetMonsterName`;
- 地图名用服务端地图编号 → 地图目录(`MAPS`,取自服务端 `map/index`)在 `localeInfo.MINIMAP_ZONE_NAME_DICT` 中查找;
- 找不到时显示“地图N”。
## 提醒
- 提醒的键是 (vnum, 地图, 频道, x, y)。
- 窗口关闭时,提醒过的 Boss 计时到期 2 秒后,客户端会主动查询一次。
- 只有新快照显示它存活时,聊天框才提示“X 已在 Y 刷新”,然后清除这条提醒;只到计时不提示。
- 服务器不再列出的 Boss 会被移出提醒。
- 离开游戏(换线、换角色)时,清空快照和提醒。
## 客户端
- 模块 `mt_boss`(`src/platform/ScriptLib/BossScript.inc`),在 `PythonBoot.cpp` 中安装,挂接 `game.GameWindow.Open/Close`。
- `FeatureServiceScript.inc`:
- 新增 `bosses` 种类和 `boss` 行解析(13 项,X/Y 有符号);
- 校验 vnum/地图/周期非 0、频道 ≤ 255、alive ≤ max ≤ 255;
- 一次最多 128 行。
## 证据
- `tests/wiki/test_boss.py`(CTest:`port.boss`)共 5 项通过,覆盖:
- 入口位置、各状态文字、坐标、分页;
- 只在确认刷新后提示;
- 未启用和空列表的提示;
- 关闭时复位;
- 地图表。
- `tests/wiki/test_service.py` 新增 `boss` 行和旧服务端(cap 255)返回 unsupported 的测试。
- 2026-10-15 联机测试(203,macOS 原生客户端,账号 admin):
- 临时开了两个 channel5 核心:13040 放地图 1/21/41/68,13041 放地图 72/5。
- 从任一核心进入游戏,窗口都列出两个核心的 5 个 Boss(海盗 5001 ×2、2307、1192、5161),倒计时一致。
- 截图确认布局正常。测试后 channel5 已恢复原配置。
## 限制和未完成
- 只列出有定时刷新的 Boss 刷新点(regen 文件里 `time > 0`);由任务或事件刷出的 Boss 不在列表中。
- 共享频道(game99)的 Boss 要等 game99 换上新服务端才会出现。
- 副本内地图(如 5、72)在 `MINIMAP_ZONE_NAME_DICT` 中没有名称,显示“地图N”。
- macOS 桌面客户端没有中文字体,窗口文字显示为 `?`。
- Android 真机测试未做。
+44
View File
@@ -0,0 +1,44 @@
# AVA2 批量开箱适配进度(v1)
2026-10-15。修改了 metin2-client 和 metin2-server,AVA2 代码只作参考(`ENABLE_MULTI_CHEST`:`uiinventory.py` 的 Ctrl + 右键、`uichestdropinfo.py`、服务端 `do_chest_drop` / `CHARACTER::OpenChest`)。服务端规则和协议见 `metin2-server/docs/FEATURE-CHEST.md`。
## 与 AVA2 的差异
| 项目 | AVA2 | 本实现 |
| --- | --- | --- |
| 触发 | Ctrl + 右键打开带滑块的窗口;Ctrl + Z + 右键直接开整叠 | Ctrl + 右键打开数量窗口(1 / 10 / 50 / 全部),点“开启”;没有直接开整叠的组合键 |
| 命令 | `/chest_drop WINDOW CELL COUNT` | `/mt_chest 1 open CELL COUNT`,不新增包头 |
| 开箱过程 | 重写的 `GiveItemFromSpecialItemGroupNew` / `AutoGiveItemChest`,单次最多 1000 | 每个礼盒都调用原 `UseItem` 礼盒路径,检查、奖励组抽取、金币/经验、日志、扣除都不变;单次最多 200 |
| 范围 | 一叠 | 同一种礼盒,先开选中的格子,再开背包里其他格子(203 上多数礼盒不叠加) |
| 背包满 | 由 AutoGiveItemChest 处理 | 每开一个前要求至少 3 格空位,不足就停止,奖励不会掉在地上 |
| 不允许批量 | — | 奖励组含刷怪、怪物组、减速、中毒、吸血的礼盒,以及非 ITEM_GIFTBOX 的物品(例如带任务脚本的宝箱) |
## 客户端
- 模块 `mt_chest`(`src/platform/ScriptLib/ChestScript.inc`),在 `PythonBoot.cpp` 中安装。替换了 `uiInventory.InventoryWindow.UseItemSlot`:按住 Ctrl 右键 ITEM_GIFTBOX 时打开窗口,其他情况调用原方法。原方法本身不使用 Ctrl(联机时检查过它的 `co_names`)。
- `PythonItemModule.cpp` 新导出 `item.ITEM_TYPE_GIFTBOX`。
- 窗口显示礼盒名称、背包内总数、数量按钮(`【】` 表示已选;“全部”最多 200)、开启按钮和上次结果。选中格子里的礼盒被移走时,自动改用背包里同一种礼盒的其他格子。
- 等待回复时,以及两次发送间隔不足 0.5 秒时,“开启”按钮不可用。
- 结果:聊天框一行“开启 N 个,金币 +N(停止原因)”,之后每行最多 5 种获得的物品(名称 ×数量)。单个礼盒的提示由服务端暂存,不再逐条刷屏;被原路径拒绝时转发一次拒绝提示。
- 3 秒没有回复:在聊天框提示一次“服务器尚未启用批量开启”,之后 Ctrl + 右键也走原来的单个使用;再收到回复会自动恢复。
- 经验不在汇总里(服务端只汇报背包物品和金币变化)。
## 证据
- `tests/wiki/test_chest.py`(CTest:`port.chest`)共 6 项通过,覆盖:
- 发送一次、等待回复、获得行累积到 done、数量上限 200、负的金币差、发送间隔;
- error 解析,畸形行和其他前缀;
- 超时后标记不支持,迟到的回复会恢复;
- 聊天汇总行(停止原因、金币、每行 5 种);
- 钩子:不按 Ctrl 和非礼盒走原方法,Ctrl + 右键礼盒打开窗口,“全部”,选中格子消失后改用其他格子,命令拦截,超时后回退,窗口关闭;
- 与服务端 `port_chest.h` 的常量、错误码和停止原因一致。
- `tests/wiki` 全部 57 项通过(1 项跳过)。
- 2026-10-15 在 203 channel5 测试核心(13040,独立二进制)用 macOS 客户端以 [SA]Admin 联机验收,礼盒用 `/item` 生成:
- 50037(可叠加,30 个)开 10 个:`done 50037 10 10 done 0`,获得 6 种物品,背包差值与 `MTCH1 got` 完全一致;
- 50070(不叠加,4 个分在 4 格)开全部:`done 50070 4 4 done 100000`,跨格子全部开启,金币 +100000 与余额变化一致;
- 71036(奖励组刷怪):`error kind`,没有扣除;
- 连发两条命令:第二条 `error rate`;
- 50037 剩余 20 个开全部:`done 50037 20 20 done 0`,获得 11 种;
- 不按 Ctrl 右键:原单个使用,礼盒正常扣除;
- 日志库只有原路径写的 `SYSTEM`、`TREASURE_EXP`、`TREASURE_GOLD` 行;syserr 没有新错误(只有原有的 `new_quest_lv52` LUA_ERROR)。
- 未部署 203 正式环境,未做 Android 真机测试;触屏没有 Ctrl,暂无触屏入口。
+4
View File
@@ -124,3 +124,7 @@
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。
2026-10-15 世界 Boss 追踪(AVA2 uitrack 世界 Boss 页,只读,不含传送):服务端各核心用原 HEADER_GG_RELAY(名字 #mt_boss)共享定时 Boss 刷新点,旧核心忽略;客户端 mt_boss 窗口 + 刷新提醒,查询种类 bosses(能力位 256);已在 203 两个 channel5 测试核心上做跨核心联机验收,正式核心尚未部署。见 AVA2-BOSS.md。
2026-10-15 属性锁定(阶段 6 后半,参考 AVA2 ENABLE_LOCK_ATTR):服务端新表 mt_item_attr_lock(按物品 ID 存锁定掩码,各核心启动时自动建表;不改动物品结构、db 缓存和客户端封包),CItem::ChangeAttribute 保留锁定槽位,手动、自动、GM 洗练全部生效;精炼时锁定随属性复制;最多 2 组,加成武器的 0/1 槽算一组;锁定免费。客户端在自动洗练窗口里加 5 个锁定按钮。已在 203 channel5 测试核心联机验收(洗 10 次锁定的 2 条不变,重新登录后仍在);2026-10-15 16:08 部署到 203 正式环境(服务端 dc71593),CH1 复验通过;未做 Android 真机测试。见 AVA2-SWITCHBOT.md 和服务端 FEATURE-ATTR-LOCK.md。
2026-10-15 批量开箱(阶段 3 的交互子批,参考 AVA2 ENABLE_MULTI_CHEST /chest_drop):服务端 mt_chest 对同一种礼盒(ITEM_GIFTBOX)逐个调用原 UseItem 开箱路径,可跨格子(203 上多数礼盒不叠加),单次最多 200 个,背包少于 3 格空位即停止;奖励组含刷怪/减速/中毒/吸血的礼盒不允许批量。客户端 Ctrl + 右键礼盒打开数量窗口(1/10/50/全部),结果汇总到聊天框。已在 203 channel5 测试核心联机验收;未部署 203 正式环境,未做 Android 真机测试和触屏入口。见 AVA2-CHEST.md 和服务端 FEATURE-CHEST.md。
+20 -3
View File
@@ -1,4 +1,4 @@
# AVA2 自动洗练适配进度(v1,不含属性锁定)
# AVA2 自动洗练适配进度(v1 + 属性锁定)
2026-10-15。修改了 metin2-client 和 metin2-server,AVA2 代码只作参考。服务端规则和协议见 `metin2-server/docs/FEATURE-SWITCHBOT.md`。
@@ -23,9 +23,26 @@
- 命令间隔至少 0.3 秒,同一时间只有一个请求在等待回复。4 秒没有回复就显示“服务器尚未启用自动洗练”。`attrs` 只接受完整、连续的回复,不完整的整批丢弃。
- 文字都用 GBK 可编码的字符(不用 ◀/▶/⚠)。
## 属性锁定(2026-10-15)
- 服务端规则、存储和协议见 `metin2-server/docs/FEATURE-ATTR-LOCK.md`。锁定的槽位在所有洗练方式下都保持不变:手动用道具、自动洗练、GM 命令。
- 窗口底部“开始/停止”右边有 5 个按钮,每条有属性的普通槽一个:`锁N` 表示未锁,`【锁N】` 表示已锁。点击切换。选属性时和洗练中不能点。
- 当前属性行里,已锁的属性前面加 `[锁]`。状态行提示“已锁定的属性在每次洗练中保持不变”。
- 服务端在 `attrs_end` 之后下发 `MTSB1 lock CELL VNUM MASK`。旧服务端不发这一行,所以不显示按钮。
- 错误提示:`slot`(该条属性不能锁定),`max`(最多锁定 2 条,且至少留 1 条可洗),`db`(保存失败)。
- 与 AVA2 的差异:
- 锁定免费。AVA2 每次锁定或解锁消耗 50348/50349,203 的 item_proto 里没有这两个道具。
- 锁定状态存在服务端独立表里,不占属性槽。
- 不要求物品正好有 5 条属性,但至少要留 1 条不锁。
- 联机测试(channel5 13040,盔甲 11209,背包 19 格):
- 锁第 2、4 条后,自动洗 10 次,这两条每次都不变,其余 3 条每次都变;
- 锁第 3 组时提示 max;
- 重新登录后锁定状态仍在;
- 解锁后表里的行被删除。
## 证据
- `tests/wiki/test_switchbot.py`(CTest:`port.switchbot`)共 6 项通过,覆盖:
- `tests/wiki/test_switchbot.py`(CTest:`port.switchbot`)共 7 项通过(第 7 项是锁定协议和按钮),覆盖:
- 请求节流和合并;
- 不完整的 attrs 回复被拒绝;
- start 命令的拼装和校验;
@@ -54,4 +71,4 @@
- Android 真机测试。
- macOS 构建需要 `-DMT_40250_SOURCE=<含 EterPack/EterPack.cpp 的源码目录>` 来生成 pack 密钥,否则 system.py 读不出来(RunMain Error)。本机没有 40250 源码,这次用的是 AVA2 的 `TEST/3. Source BIN/Client`,两者密钥相同。
- 服务端还没有部署到 203 正式环境。
- 属性锁定(阶段 6 后半):需要单独的存储设计。
- 属性锁定已完成(见上),2026-10-15 16:08 已部署到 203 正式环境(服务端 dc71593),CH1 联机验收通过。
+247
View File
@@ -0,0 +1,247 @@
// PORT: AVA2 uitrack world-boss tab, read-only. The server's boss regens (own channel plus the shared core) come
// from the MTF1 'bosses' query; the original regen timers stay authoritative. AVA2's teleport button is left out.
// See docs/AVA2-BOSS.md.
static const char c_szBossScript[] = R"PY(# -*- coding: utf-8 -*-
import app
import chat
import game
import grp
import nonplayer
import ui
import weakref
import wndMgr
import mt_feature_service
from mt_biolog import Action, Text, L
try:
import localeInfo
except ImportError:
localeInfo=None
g_window=None
g_entry=None
g_tick=None
PAGE=8
REFRESH=30.
SHARED_CHANNEL=99
# Server map index -> map directory (share/locale/<locale>/map/index), for localeInfo.MINIMAP_ZONE_NAME_DICT.
MAPS={1:'metin2_map_a1',3:'metin2_map_a3',4:'metin2_map_guild_01',5:'metin2_map_monkey_dungeon_11',
6:'metin2_guild_village_01',21:'metin2_map_b1',23:'metin2_map_b3',24:'metin2_map_guild_02',
25:'metin2_map_monkey_dungeon_12',26:'metin2_guild_village_02',41:'metin2_map_c1',43:'metin2_map_c3',
44:'metin2_map_guild_03',45:'metin2_map_monkey_dungeon_13',46:'metin2_guild_village_03',61:'map_n_snowm_01',
62:'metin2_map_n_flame_01',63:'metin2_map_n_desert_01',64:'map_n_threeway',65:'metin2_map_milgyo',
66:'metin2_map_deviltower1',67:'metin2_map_trent',68:'metin2_map_trent02',69:'season1/metin2_map_WL_01',
70:'season1/metin2_map_nusluck01',71:'metin2_map_spiderdungeon_02',72:'metin2_map_skipia_dungeon_01',
73:'metin2_map_skipia_dungeon_02',81:'metin2_map_wedding_01',100:'metin2_map_fielddungeon',
101:'metin2_map_resources_zon',103:'metin2_map_t1',104:'metin2_map_spiderdungeon',105:'metin2_map_t2',
107:'metin2_map_monkey_dungeon',108:'metin2_map_monkey_dungeon2',109:'metin2_map_monkey_dungeon3',
110:'metin2_map_t3',111:'metin2_map_t4',112:'metin2_map_duel',113:'metin2_map_oxevent',
114:'metin2_map_sungzi',118:'metin2_map_sungzi_flame_hill_01',119:'metin2_map_sungzi_flame_hill_02',
120:'metin2_map_sungzi_flame_hill_03',121:'metin2_map_sungzi_snow',122:'metin2_map_sungzi_snow_pass01',
123:'metin2_map_sungzi_snow_pass02',124:'metin2_map_sungzi_snow_pass03',125:'metin2_map_sungzi_desert_01',
126:'metin2_map_sungzi_desert_hill_01',127:'metin2_map_sungzi_desert_hill_02',
128:'metin2_map_sungzi_desert_hill_03',181:'metin2_map_empirewar01',182:'metin2_map_empirewar02',
183:'metin2_map_empirewar03',200:'gm_guild_build',208:'metin2_map_skipia_dungeon_boss',
216:'metin2_map_devilcatacomb',217:'metin2_map_spiderdungeon_03',301:'Metin2_map_CapeDragonHead',
302:'metin2_map_dawnmistwood',303:'metin2_map_BayBlackSand',304:'metin2_map_Mt_Thunder',
351:'metin2_map_n_flame_dungeon_01'}
def Duration(seconds):
seconds=max(0,int(seconds))
return '%02d:%02d:%02d'%(seconds//3600,(seconds//60)%60,seconds%60)
def MapName(index):
names=getattr(localeInfo,'MINIMAP_ZONE_NAME_DICT',{})
name=names.get(MAPS.get(index,''))
return name if name else L('地图%d'%index)
def BossName(vnum):
try:name=nonplayer.GetMonsterName(vnum)
except Exception:name=''
return name if name else L('Boss %d'%vnum)
def Key(row):return (row['vnum'],row['map'],row['channel'],row['x'],row['y'])
def Rows(data):
rows=[]
for v in data['rows']:
vnum,map_index,x,y,channel,alive,most,next_time,period=v
rows.append(dict(vnum=vnum,map=map_index,x=x,y=y,channel=channel,alive=alive,max=most,next=next_time,period=period))
return rows
class Tracker(object):
# Server snapshot plus the per-boss spawn reminders; a reminder only fires on a fresh snapshot.
def __init__(self,now,notify):
self.now=now;self.notify=notify;self.rows=None;self.serverTime=0;self.received=0;self.error=None
self.reminders=set()
def Apply(self,data,error):
if error:self.error=error;self.rows=None;return
self.error=None;self.serverTime=data['time'];self.received=self.now();rows=Rows(data)
alive=set(Key(r) for r in rows if r['alive'])
for key in sorted(self.reminders&alive):self.notify(key);self.reminders.discard(key)
self.reminders&=set(Key(r) for r in rows) # a boss the server no longer lists cannot be announced
self.rows=rows
def Now(self):return self.serverTime+max(0,self.now()-self.received)
def Left(self,row):return max(0,row['next']-self.Now()) if row['next'] else None
def Toggle(self,row):
key=Key(row)
if key in self.reminders:self.reminders.discard(key)
elif not row['alive']:self.reminders.add(key)
def Due(self):
# A reminded boss whose regen timer has passed: ask the server whether it really spawned.
if not self.rows:return False
return any(Key(r) in self.reminders and r['next'] and self.Now()>=r['next']+2 for r in self.rows)
class BossWindow(ui.Window):
def __init__(self,tracker):
ui.Window.__init__(self);self.SetWindowName('BossTrackWindow');self.AddFlag('float');self.AddFlag('movable')
self.tracker=tracker;self.pending=False;self.generation=0;self.nextQuery=0;self.page=0;self.dimensions=None
self.heading=Text(self,18,18,'世界Boss',0xffffd68b)
self.closeButton=Action(self,0,6,60,'关闭',self.Hide)
self.refreshButton=Action(self,18,48,80,'刷新',self.Query)
self.prevButton=Action(self,110,48,72,'上一页',lambda:self.Turn(-1))
self.nextButton=Action(self,194,48,72,'下一页',lambda:self.Turn(1))
self.status=Text(self,280,54,'',0xffc3b7a1)
self.lines=[Text(self,18,0,'',0xffefdfc3) for i in range(PAGE)]
self.details=[Text(self,30,0,'',0xffb2aa9a) for i in range(PAGE)]
self.remindButtons=[Action(self,0,0,92,'',lambda i=i:self.Remind(i)) for i in range(PAGE)]
self.note=Text(self,18,0,'提醒:Boss 刷新后在聊天框提示;以服务器刷新为准。',0xffb2aa9a)
self.Reflow();self.Hide()
def Buttons(self):return [self.closeButton,self.refreshButton,self.prevButton,self.nextButton]+self.remindButtons
def Open(self):
self.Reflow();self.SetCenterPosition();self.Show();self.SetTop();self.Query()
def Query(self):
if self.pending:return
self.pending=True;self.generation+=1;generation=self.generation
self.refreshButton.SetEnabled(False);self.status.SetText(L('正在同步…'))
def received(data,error):
if generation!=self.generation:return
self.pending=False;self.refreshButton.SetEnabled(True);self.nextQuery=app.GetTime()+REFRESH
self.tracker.Apply(data,error);self.Render()
if mt_feature_service.g_service:mt_feature_service.g_service.Request('bosses',0,0,received)
else:received(None,'unsupported')
def Turn(self,step):
self.page=max(0,min(self.Pages()-1,self.page+step));self.Render()
def Pages(self):
rows=self.tracker.rows or []
return max(1,(len(rows)+PAGE-1)//PAGE)
def Remind(self,i):
rows=self.tracker.rows or [];index=self.page*PAGE+i
if index<len(rows):self.tracker.Toggle(rows[index]);self.Render()
def Render(self):
t=self.tracker;rows=t.rows or [];self.page=min(self.page,self.Pages()-1)
if t.error:self.status.SetText(L('服务端未启用 Boss 追踪' if t.error=='unsupported' else '未同步,请稍后刷新'))
elif t.rows is None:self.status.SetText(L('正在同步…'))
elif not rows:self.status.SetText(L('本频道没有定时刷新的 Boss'))
else:self.status.SetText(L('第 %d/%d 页,共 %d 个'%(self.page+1,self.Pages(),len(rows))))
self.prevButton.SetEnabled(self.page>0);self.nextButton.SetEnabled(self.page+1<self.Pages())
for i in range(PAGE):
index=self.page*PAGE+i;line=self.lines[i];detail=self.details[i];button=self.remindButtons[i]
if index>=len(rows):line.Hide();detail.Hide();button.Hide();continue
r=rows[index];left=t.Left(r)
channel='共享' if r['channel']==SHARED_CHANNEL else 'CH%d'%r['channel']
line.SetText(L('[%s] '%channel)+BossName(r['vnum'])+L(' ')+MapName(r['map']))
if r['alive']:state='存活 %d/%d'%(r['alive'],r['max'])
elif left is None:state='不再刷新'
elif left:state='刷新倒计时 '+Duration(left)
else:state='即将刷新'
where='随机位置' if not r['x'] and not r['y'] else '坐标 (%d, %d)'%(r['x']//100,r['y']//100)
detail.SetText(L('%s · %s · 周期 %s'%(state,where,Duration(r['period']))))
button.SetText(L('提醒:'+('开' if Key(r) in t.reminders else '关')))
button.SetEnabled(bool(r['alive']==0 and r['next']) or Key(r) in t.reminders)
line.Show();detail.Show();button.Show()
def Reflow(self):
dims=(wndMgr.GetScreenWidth(),wndMgr.GetScreenHeight())
if dims==self.dimensions:return
self.dimensions=dims;width=min(620,max(460,dims[0]-16));height=min(560,max(360,dims[1]-16));self.SetSize(width,height)
self.closeButton.SetPosition(width-76,6)
spacing=max(36,min(56,(height-140)//PAGE))
for i in range(PAGE):
y=88+i*spacing
self.lines[i].SetPosition(18,y);self.details[i].SetPosition(30,y+18);self.remindButtons[i].SetPosition(width-110,y)
self.note.SetPosition(18,height-22);self.SetCenterPosition()
def OnUpdate(self):
self.Reflow();self.Render()
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.generation+=1;self.Hide()
for b in self.Buttons():b.event=None
class ReminderTick(ui.Window):
# Keeps the snapshot fresh while the window is open, and checks due reminders while it is closed.
def __init__(self):
ui.Window.__init__(self);self.AddFlag('not_pick');self.SetSize(0,0);self.Show()
def OnUpdate(self):
w=g_window
if not w or w.pending or app.GetTime()<w.nextQuery:return
if w.IsShow() or g_tracker.Due():w.Query()
class Entry(Action):
def __init__(self,window):
Action.__init__(self,None,0,0,64,'Boss',Toggle)
self.minimap=weakref.proxy(window.interface.wndMiniMap);self.SetWindowName('BossEntry');self.OnUpdate()
def OnUpdate(self):
x,y=self.minimap.GetGlobalPosition();self.SetPosition(max(4,x-68),y+356)
def Announce(key):
vnum,map_index,channel,x,y=key
chat.AppendChat(chat.CHAT_TYPE_INFO,BossName(vnum)+L(' 已在 ')+MapName(map_index)+L(' 刷新'))
g_tracker=Tracker(app.GetTime,Announce)
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,g_tick
_open(self);g_window=BossWindow(g_tracker);g_entry=Entry(self);g_tick=ReminderTick()
def Close(self):
global g_window,g_entry,g_tick
if g_tick:g_tick.Hide();g_tick=None
if g_entry:g_entry.Hide();g_entry.event=None;g_entry=None
if g_window:g_window.Destroy();g_window=None
g_tracker.rows=None;g_tracker.reminders=set() # another channel/character lists other bosses
_close(self)
game.GameWindow.Open=Open
game.GameWindow.Close=Close
)PY";
+219
View File
@@ -0,0 +1,219 @@
// PORT: AVA2-style batch chest opening (ENABLE_MULTI_CHEST, Ctrl + right click on a gift box), driven by the
// server's /mt_chest command. Every box still goes through the original gift-box use path on the server; this
// window only picks the box and the count and shows the summed gains. Without Ctrl, or against a server without
// the command, the original single use runs. Protocol: metin2-server docs/FEATURE-CHEST.md.
static const char c_szChestScript[] = R"PY(# -*- coding: utf-8 -*-
import app
import chat
import grp
import item
import net
import player
import ui
import uiInventory
import game
from mt_biolog import Action, Text, L
from mt_wiki import B
g_window=None
MAX=200
COUNTS=(1,10,50)
SEND_GAP=.5
TIMEOUT=3.
GIFTBOX=getattr(item,'ITEM_TYPE_GIFTBOX',23)
CHAT_ITEMS=5
ERRORS={'rate':'操作过快','invalid':'参数无效','busy':'当前状态不能开启宝箱','item':'宝箱已不在原位置',
'kind':'这种宝箱不能批量开启,请单个开启','full':'背包空位不足,至少保留 3 格'}
REASONS={'done':'','empty':'宝箱已全部开启','full':'背包空位不足,已停止','busy':'状态变化,已停止','rejected':'宝箱无法开启,已停止'}
def Number(text,low=0,high=4294967295):
sign=-1 if text[:1]=='-' else 1
digits=text[1:] if sign<0 else text
if not digits.isdigit() or len(digits)>12:raise ValueError(text)
value=sign*int(digits)
if not low<=value<=high:raise ValueError(text)
return value
class Opener(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.waiting=None;self.nextSend=0;self.unsupported=False
self.gains=[];self.result=None;self.error=None
def Busy(self):return self.waiting is not None or self.now()<self.nextSend
def Open(self,cell,count):
self.Tick()
if self.unsupported or self.Busy():return False
now=self.now();count=max(1,min(MAX,int(count)))
self.send('/mt_chest 1 open %d %d'%(cell,count))
self.waiting=now+TIMEOUT;self.nextSend=now+SEND_GAP;self.gains=[];self.error=None
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('MTCH1 '):return False
words=line.split()
try:
if words[1]=='got' and len(words)==4:
self.gains.append((Number(words[2]),Number(words[3],1)));return True
if words[1]=='done' and len(words)==7 and words[5] in REASONS:
vnum,asked,opened=[Number(w,0,100000000) for w in words[2:5]]
self.result=dict(vnum=vnum,asked=asked,opened=opened,reason=words[5],
gold=Number(words[6],-2**62,2**62),gains=self.gains)
self.gains=[];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 ItemName(vnum):
item.SelectItem(vnum);return item.GetItemName()
def Batchable(vnum):
if not vnum:return False
item.SelectItem(vnum);return item.GetItemType()==GIFTBOX
def Summary(result):
# Chat lines for one finished batch: the count line, then the gains a few items per line.
lines=['批量开启 %s:开启 %d 个'%(ItemName(result['vnum']),result['opened'])+
(',金币 %+d'%result['gold'] if result['gold'] else '')+
('(%s)'%REASONS[result['reason']] if REASONS[result['reason']] else '')]
gains=['%s ×%d'%(ItemName(vnum),count) for vnum,count in result['gains']]
for i in range(0,len(gains),CHAT_ITEMS):lines.append('获得:'+','.join(gains[i:i+CHAT_ITEMS]))
return lines
class ChestWindow(ui.Window):
def __init__(self,opener):
ui.Window.__init__(self);self.SetWindowName('ChestWindow');self.AddFlag('float');self.AddFlag('movable')
self.opener=opener;self.cell=-1;self.vnum=0;self.count=1;self.SetSize(332,286)
self.heading=Text(self,18,18,'批量开启宝箱',0xffffd68b)
self.closeButton=Action(self,256,6,60,'关闭',self.Hide)
self.name=Text(self,18,58,'',0xffe8dec8)
self.owned=Text(self,18,82,'',0xffc3b7a1)
self.countButtons=[Action(self,18+i*76,108,68,'',lambda count=count:self.SetCount(count)) for i,count in enumerate(COUNTS)]
self.allButton=Action(self,246,108,68,'全部',lambda:self.SetCount(MAX))
self.openButton=Action(self,18,170,296,'',self.OpenBoxes)
self.status=Text(self,18,234,'',0xffc3b7a1)
self.hint=Text(self,18,258,'Ctrl + 右键宝箱打开本窗口,单次最多 %d 个'%MAX,0xff8f8676)
self.Hide()
def Buttons(self):return [self.closeButton,self.allButton,self.openButton]+self.countButtons
def Select(self,cell,vnum):
if self.vnum!=vnum:self.count=1;self.opener.result=None;self.opener.error=None
self.cell=cell;self.vnum=vnum;self.Refresh();self.SetCenterPosition();self.Show();self.SetTop()
def Owned(self):return player.GetItemCountByVnum(self.vnum) if self.vnum else 0
def Amount(self):return max(1,min(self.count,self.Owned(),MAX))
def SetCount(self,count):self.count=count;self.Refresh()
def Cell(self):
# The chosen cell while it still holds the box, otherwise any bag cell that does (the server does the same).
if player.GetItemIndex(self.cell)==self.vnum:return self.cell
for cell in range(player.INVENTORY_PAGE_SIZE*player.INVENTORY_PAGE_COUNT):
if player.GetItemIndex(cell)==self.vnum:return cell
return -1
def OpenBoxes(self):
cell=self.Cell()
if cell<0:self.Refresh();return
if self.opener.Open(cell,self.Amount()):self.cell=cell
self.Refresh()
def Refresh(self):
owned=self.Owned()
self.name.SetText(L(B(ItemName(self.vnum)) if self.vnum else ''))
self.owned.SetText(L('背包内共 %d 个'%owned))
for button,count in zip(self.countButtons,COUNTS):
button.SetText(L('【%d】'%count if self.count==count else '%d'%count));button.SetEnabled(owned>0)
self.allButton.SetText(L('【全部】' if self.count==MAX else '全部'));self.allButton.SetEnabled(owned>0)
self.openButton.SetText(L('开启 %d 个'%self.Amount() if owned else '没有宝箱'))
self.openButton.SetEnabled(owned>0 and not self.opener.Busy() and not self.opener.unsupported)
self.status.SetText(L(self.StatusText()))
def StatusText(self):
o=self.opener
if o.unsupported:return '!服务器尚未启用批量开启'
if o.waiting is not None:return '正在开启……'
if o.error:return '!'+ERRORS[o.error]
r=o.result
if r and r['vnum']==self.vnum:
text='上次:开启 %d/%d 个,获得 %d 种物品'%(r['opened'],min(r['asked'],r['opened']+self.Owned()),len(r['gains']))
return text+(','+REASONS[r['reason']] if REASONS[r['reason']] 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):
busy=self.opener.Busy();self.opener.Tick()
if busy and not self.opener.Busy():self.Refresh() # the send gap ran out, or the request timed out
def OnPressEscapeKey(self):self.Hide();return True
def Destroy(self):
self.Hide()
for b in self.Buttons():b.event=None
def OnOpener(kind):
if kind=='unsupported':chat.AppendChat(chat.CHAT_TYPE_INFO,L('服务器尚未启用批量开启,请单个开启宝箱'))
elif kind=='done':
for line in Summary(g_opener.result):chat.AppendChat(chat.CHAT_TYPE_INFO,L(line))
elif kind=='error':chat.AppendChat(chat.CHAT_TYPE_INFO,L(ERRORS[g_opener.error]))
if g_window:g_window.Refresh()
g_opener=Opener(net.SendChatPacket,app.GetTime,OnOpener)
def CtrlPressed():return app.IsPressed(app.DIK_LCONTROL) or app.IsPressed(app.DIK_RCONTROL)
_open=game.GameWindow.Open
_close=game.GameWindow.Close
_command=game.GameWindow.BINARY_ServerCommand_Run
_use=uiInventory.InventoryWindow.UseItemSlot
def Open(self):
global g_window
_open(self);g_opener.waiting=None;g_window=ChestWindow(g_opener)
def Close(self):
global g_window
if g_window:g_window.Destroy();g_window=None
_close(self)
def Command(self,line):
if g_opener.Receive(line):return 1
return _command(self,line)
def UseItemSlot(self,slot):
if g_window and not g_opener.unsupported and CtrlPressed():
cell=self._InventoryWindow__InventoryLocalSlotPosToGlobalSlotPos(slot)
vnum=player.GetItemIndex(cell)
if Batchable(vnum):g_window.Select(cell,vnum);return
return _use(self,slot)
game.GameWindow.Open=Open
game.GameWindow.Close=Close
game.GameWindow.BINARY_ServerCommand_Run=Command
uiInventory.InventoryWindow.UseItemSlot=UseItemSlot
)PY";
@@ -6,7 +6,8 @@ import net
import ui
from mt_wiki_data import Number
BITS={'mob':1,'chest':2,'stats':4,'sources':8,'dungeons':16,'calendar':32}
BITS={'mob':1,'chest':2,'stats':4,'sources':8,'dungeons':16,'calendar':32,'bosses':256}
WHOLE=('stats','dungeons','bosses') # one reply with every row; no subject or page
g_service=None
g_tick=None
_serial=0
@@ -27,7 +28,7 @@ class Service(object):
global _serial
if kind not in BITS or not 0<=subject<=4294967295 or not 0<=offset<=4096 or len(self.queue)>=8:
callback(None,'invalid');return 0
if (kind in ('stats','dungeons') and (subject or offset)) or (kind=='calendar' and subject!=1):
if (kind in WHOLE and (subject or offset)) or (kind=='calendar' and subject!=1):
callback(None,'invalid');return 0
_serial=(_serial%2147483647)+1
self.queue.append(dict(id=_serial,kind=kind,subject=subject,offset=offset,callback=callback,retries=0))
@@ -53,7 +54,7 @@ class Service(object):
if not self.mask&BITS[p['kind']]:
self.Finish(None,'unsupported');return
text='/mt_features 1 %d %s'%(p['id'],p['kind'])
if p['kind'] not in ('stats','dungeons'):text+=' %d %d'%(p['subject'],p['offset'])
if p['kind'] not in WHOLE:text+=' %d %d'%(p['subject'],p['offset'])
net.SendChatPacket(text)
self.deadline=now+4.0;self.nextSend=now+0.3
@@ -80,15 +81,15 @@ class Service(object):
elif op=='begin' and len(w)==9 and p['kind']!='cap':
if 'result' in p or w[3]!=p['kind'] or Number(w[4])!=p['subject'] or Number(w[5])!=p['offset']:
raise ValueError('mismatched response')
total=Number(w[6],128 if p['kind'] in ('stats','dungeons') else 256 if p['kind']=='calendar' else 4096)
total=Number(w[6],128 if p['kind'] in WHOLE else 256 if p['kind']=='calendar' else 4096)
if total<p['offset']:raise ValueError('invalid page')
p['result']=dict(kind=w[3],subject=p['subject'],offset=p['offset'],total=total,mode=Number(w[7],11),
time=Number(w[8]),rows=[])
elif op in ('row','stat','event') and 'result' in p:
elif op in ('row','stat','event','boss') and 'result' in p:
result=p['result'];rows=result['rows']
limit=result['total'] if p['kind'] in ('stats','dungeons') else min(8,result['total']-p['offset'])
limit=result['total'] if p['kind'] in WHOLE else min(8,result['total']-p['offset'])
if len(rows)>=limit or Number(w[3])!=p['offset']+len(rows):raise ValueError('invalid row order')
if op=='row' and len(w)==12 and p['kind'] not in ('stats','dungeons','calendar'):
if op=='row' and len(w)==12 and p['kind'] not in WHOLE+('calendar',):
values=[Number(v) for v in w[4:]]
if values[2] not in (0,1,2,3,4,5,10,11,20,21) or not values[0]:raise ValueError('invalid row')
rows.append(values)
@@ -97,12 +98,17 @@ class Service(object):
if not values[0] or values[1] not in (1,2) or values[2]>=values[3] or values[4]>255 or values[5]>3 or values[6]>1:raise ValueError('invalid calendar event')
if any(r[0]==values[0] for r in rows):raise ValueError('duplicate event')
rows.append(values)
elif op=='boss' and len(w)==13 and p['kind']=='bosses':
# VNUM MAP X Y CHANNEL ALIVE MAX NEXT PERIOD; X/Y are map-local and may be negative.
values=[Number(w[4]),Number(w[5]),Signed(w[6]),Signed(w[7])]+[Number(v) for v in w[8:]]
if not values[0] or not values[1] or values[4]>255 or values[6]>255 or values[5]>values[6] or not values[8]:raise ValueError('invalid boss')
rows.append(values)
elif op=='stat' and len(w)==6 and p['kind'] in ('stats','dungeons'):
if not w[4].replace('_','').isalpha() or len(w[4])>32 or any(r[0]==w[4] for r in rows):raise ValueError('invalid stat')
rows.append((w[4],Signed(w[5])))
else:raise ValueError('invalid row format')
elif op=='end' and len(w)==4 and 'result' in p:
result=p['result'];expected=result['total'] if p['kind'] in ('stats','dungeons') else min(8,result['total']-p['offset'])
result=p['result'];expected=result['total'] if p['kind'] in WHOLE else min(8,result['total']-p['offset'])
if Number(w[3])!=expected or len(result['rows'])!=expected:raise ValueError('incomplete reply')
if p['kind']=='dungeons':
values=dict(result['rows'])
+4
View File
@@ -1001,8 +1001,10 @@ namespace PythonBoot
#include "WikiEntryScript.inc"
#include "SwitchbotScript.inc"
#include "PickupScript.inc"
#include "ChestScript.inc"
#include "DisplayScript.inc"
#include "ChannelScript.inc"
#include "BossScript.inc"
static void install_script_module(const char* c_szModule, const char* c_szScript)
{
@@ -1078,8 +1080,10 @@ bool RunMainScript(const char* lpCmdLine, std::string* error)
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_chest", c_szChestScript);
install_script_module("mt_display", c_szDisplayScript);
install_script_module("mt_channel", c_szChannelScript);
install_script_module("mt_boss", c_szBossScript);
if (g_touch_input)
install_script_module("mt_mobile_hud", c_szMobileHUDScript);
}
+39 -6
View File
@@ -1,6 +1,7 @@
// 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.
// only picks the item, scroll and targets and shows progress. The lock buttons toggle the server-side attribute
// lock that every reroll keeps. Protocol: metin2-server docs/FEATURE-SWITCHBOT.md, FEATURE-ATTR-LOCK.md.
static const char c_szSwitchbotScript[] = R"PY(# -*- coding: utf-8 -*-
import app
import chat
@@ -21,6 +22,7 @@ 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
LOCK_GROUPS=2
SEND_GAP=.3
TIMEOUT=4.
REASONS={'running':'洗练中','matched':'已获得目标属性','limit':'已达到次数上限','no_scroll':'洗练道具已用完',
@@ -28,7 +30,8 @@ REASONS={'running':'洗练中','matched':'已获得目标属性','limit':'已达
'stopped':'已手动停止','idle':'未运行'}
ERRORS={'rate':'操作过快,请稍后','invalid':'参数无效','item':'物品不存在','equipped':'请先卸下装备或结束交易','no_attr':'该物品不能洗练',
'scroll':'没有可用的洗练道具','target':'目标属性超出可洗范围','running':'已有洗练在进行','busy':'当前状态不能洗练',
'unsupported':'服务器尚未启用自动洗练'}
'unsupported':'服务器尚未启用自动洗练','slot':'该条属性不能锁定','max':'最多锁定 2 条,且至少留 1 条可洗',
'db':'锁定保存失败,请稍后再试'}
def Number(text,low=0,high=4294967295):
@@ -43,7 +46,7 @@ class Bot(object):
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
self.allowed={};self.locks={};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
@@ -67,6 +70,14 @@ class Bot(object):
parts.append('%d %d'%(apply,value))
self.error=None;self.Enqueue('start',' '.join(parts));return None
def Lock(self,cell,slot):
if not 0<=slot<5 or cell not in self.locks:return
self.error=None;self.Enqueue('lock','/mt_switchbot 1 lock %d %d'%(cell,slot))
def LockMask(self,cell,vnum):
lock=self.locks.get(cell)
return lock[1] if lock and lock[0]==vnum else 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'])
@@ -106,6 +117,10 @@ class Bot(object):
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=='lock':
# Follows attrs_end (and answers lock). Servers without the lock never send it, so no buttons show.
if len(words)!=4:raise ValueError('lock')
self.locks[Number(words[1])]=(Number(words[2]),Number(words[3],0,31));self.Answered('lock');self.Notify('lock')
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]),
@@ -155,13 +170,14 @@ class SwitchbotWindow(ui.Window):
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.lockButtons=[Action(self,0,0,40,'',lambda i=i:self.ToggleLock(i)) for i in range(5)]
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
self.pickPrev,self.pickNext,self.startButton,self.stopButton]+self.altButtons+self.lockButtons+rows
def Open(self):
self.Reflow();self.Scan();self.SetCenterPosition();self.Show();self.SetTop();self.bot.Status();self.RequestAttrs()
@@ -181,6 +197,7 @@ class SwitchbotWindow(ui.Window):
# 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'])
if selected[0] in self.bot.locks:self.bot.locks[state['cell']]=self.bot.locks[selected[0]]
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),
@@ -235,6 +252,14 @@ class SwitchbotWindow(ui.Window):
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 Locks(self):
selected=self.Selected()
return self.bot.LockMask(*selected) if selected else None
def ToggleLock(self,slot):
selected=self.Selected()
if selected and not self.bot.Running():self.bot.Lock(selected[0],slot);self.Refresh()
def Remove(self,index):del self.alternatives[self.alt][index];self.Refresh()
def Start(self):
@@ -280,6 +305,11 @@ class SwitchbotWindow(ui.Window):
for b in (self.pickPrev,self.pickNext):
if self.picking and pages>1:b.Show()
else:b.Hide()
locks=self.Locks()
for i,b in enumerate(self.lockButtons):
filled=selected and player.GetItemAttribute(player.INVENTORY,selected[0],i)[0]
if locks is None or self.picking or not filled:b.Hide();continue
b.SetText(L(B(u'【锁%d】'%(i+1) if locks>>i&1 else u'锁%d'%(i+1))));b.SetEnabled(not running);b.Show()
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))
@@ -290,14 +320,15 @@ class SwitchbotWindow(ui.Window):
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'])
if self.Locks():return u'已锁定的属性在每次洗练中保持不变'
return u'任一方案的属性全部达标即停止;只看前 5 条普通属性'
def CurrentText(self,selected):
if not selected:return ''
parts=[]
parts=[];locks=self.Locks() or 0
for i in range(5):
apply,value=player.GetItemAttribute(player.INVENTORY,selected[0],i)
if apply:parts.append(AffectText(apply,value))
if apply:parts.append((L('[锁]') if locks>>i&1 else '')+AffectText(apply,value))
return ' / '.join(parts)
def Reflow(self):
@@ -313,6 +344,8 @@ class SwitchbotWindow(ui.Window):
bottom=height-104
self.pickPrev.SetPosition(18,bottom);self.pickNext.SetPosition(width-98,bottom)
self.startButton.SetPosition(18,bottom);self.stopButton.SetPosition(146,bottom)
step=(width-292)//5
for i,b in enumerate(self.lockButtons):b.SetPosition(274+i*step,bottom);b.SetSize(step-4,48);b.label.SetPosition((step-4)//2,24)
self.status.SetPosition(18,height-46);self.current.SetPosition(18,height-22)
self.SetCenterPosition();self.Refresh()
+4
View File
@@ -324,6 +324,10 @@ if(BUILD_TESTING AND CMAKE_SYSTEM_NAME STREQUAL CMAKE_HOST_SYSTEM_NAME)
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)
add_test(NAME port.boss
COMMAND ${MT_WIKI_PYTHON3} ${PROJECT_SOURCE_DIR}/tests/wiki/test_boss.py)
add_test(NAME port.chest
COMMAND ${MT_WIKI_PYTHON3} ${PROJECT_SOURCE_DIR}/tests/wiki/test_chest.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)
@@ -618,6 +618,7 @@ void initItem()
PyModule_AddIntConstant(poModule, "ITEM_TYPE_POLYMORPH", CItemData::ITEM_TYPE_POLYMORPH);
PyModule_AddIntConstant(poModule, "ITEM_TYPE_TREASURE_BOX", CItemData::ITEM_TYPE_TREASURE_BOX);
PyModule_AddIntConstant(poModule, "ITEM_TYPE_TREASURE_KEY", CItemData::ITEM_TYPE_TREASURE_KEY);
PyModule_AddIntConstant(poModule, "ITEM_TYPE_GIFTBOX", CItemData::ITEM_TYPE_GIFTBOX); // PORT: batch chest opening
PyModule_AddIntConstant(poModule, "ITEM_TYPE_PICK", CItemData::ITEM_TYPE_PICK);
PyModule_AddIntConstant(poModule, "ITEM_TYPE_BLEND", CItemData::ITEM_TYPE_BLEND);
PyModule_AddIntConstant(poModule, "ITEM_TYPE_DS", CItemData::ITEM_TYPE_DS);
+117
View File
@@ -0,0 +1,117 @@
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 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 Service(object):
def __init__(self):self.requests=[]
def Request(self,kind,subject,offset,callback):self.requests.append((kind,subject,offset,callback));return len(self.requests)
def Reply(self,rows,time=1700000000,error=None):
callback=self.requests[-1][3]
callback(None if error else dict(kind='bosses',subject=0,offset=0,total=len(rows),mode=0,time=time,rows=rows),error)
TRENT=[2307,68,51200,-300,1,0,1,1700000100,9000]
SKIPIA=[1192,72,0,0,1,1,1,1700028800,28800]
DESERT=[2191,999,10000,20000,99,0,1,0,1800]
class BossTests(unittest.TestCase):
def setUp(self):
self.time=100.;self.chat=[]
mods={n:types.ModuleType(n) for n in ('app','chat','game','grp','nonplayer','ui','wndMgr','localeInfo','mt_feature_service','mt_biolog')}
mods['app'].GetTime=lambda:self.time
mods['chat'].CHAT_TYPE_INFO=1;mods['chat'].AppendChat=lambda t,m:self.chat.append(m)
mods['game'].GameWindow=type('GameWindow',(),dict(Open=lambda s:None,Close=lambda s:None))
grp=mods['grp'];grp.SetColor=grp.RenderBar=grp.RenderBox=lambda *a:None
mods['nonplayer'].GetMonsterName=lambda vnum:{2307:'TreeKing',1192:'Skipia',2191:'Turtle'}.get(vnum,'')
mods['ui'].Window=Widget
mods['wndMgr'].GetScreenWidth=lambda:1280;mods['wndMgr'].GetScreenHeight=lambda:800
mods['localeInfo'].MINIMAP_ZONE_NAME_DICT={'metin2_map_trent02':'RedWood'}
self.service=Service();mods['mt_feature_service'].g_service=self.service
mods['mt_biolog'].Action=Action;mods['mt_biolog'].Text=lambda p,x,y,t='',c=0:Widget();mods['mt_biolog'].L=lambda t:t
self.previous={n:sys.modules.get(n) for n in mods}
sys.modules.update(mods)
self.ns={'__name__':'mt_boss'};exec(script('BossScript.inc'),self.ns)
self.game=sys.modules['game'];self.gw=self.game.GameWindow()
self.gw.interface=types.SimpleNamespace(wndMiniMap=Widget())
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 open(self):
self.game.GameWindow.Open(self.gw);w=self.ns['g_window'];w.Open();return w
def test_window_lists_server_rows(self):
w=self.open();self.assertEqual(self.ns['g_entry'].pos,(4,356))
self.assertEqual(self.service.requests[-1][:3],('bosses',0,0));self.assertFalse(w.refreshButton.enabled)
self.service.Reply([TRENT,SKIPIA,DESERT]);self.assertTrue(w.refreshButton.enabled)
self.assertEqual(w.lines[0].text,'[CH1] TreeKing RedWood')
self.assertEqual(w.details[0].text,'刷新倒计时 00:01:40 · 坐标 (512, -3) · 周期 02:30:00')
self.assertIn('存活 1/1',w.details[1].text);self.assertIn('随机位置',w.details[1].text)
self.assertEqual(w.lines[2].text,'[共享] Turtle 地图999');self.assertIn('不再刷新',w.details[2].text)
self.assertFalse(w.remindButtons[1].enabled) # alive
self.assertFalse(w.remindButtons[2].enabled) # no timer
self.assertFalse(w.lines[3].shown);self.assertIn('共 3 个',w.status.text)
self.time+=40;w.Render();self.assertIn('00:01:00',w.details[0].text) # counts down from the server time
def test_pages(self):
rows=[[2000+i,68,0,0,1,0,1,1700000100,600] for i in range(11)]
w=self.open();self.service.Reply(rows)
self.assertFalse(w.prevButton.enabled);self.assertTrue(w.nextButton.enabled)
w.nextButton.event();self.assertTrue(w.lines[2].shown);self.assertFalse(w.lines[3].shown);self.assertIn('第 2/2 页',w.status.text)
self.assertFalse(w.nextButton.enabled)
def test_reminder_fires_only_on_confirmed_spawn(self):
w=self.open();self.service.Reply([TRENT,SKIPIA]);w.remindButtons[0].event()
self.assertIn('开',w.remindButtons[0].text);w.Hide()
tick=self.ns['g_tick'];count=len(self.service.requests)
self.time+=50;tick.OnUpdate();self.assertEqual(len(self.service.requests),count) # not due yet
self.time+=60;tick.OnUpdate();self.assertEqual(len(self.service.requests),count+1)
self.service.Reply([TRENT,SKIPIA],time=1700000110);self.assertEqual(self.chat,[]) # timer passed, not spawned
self.assertIn(('2307',),[(str(k[0]),) for k in self.ns['g_tracker'].reminders])
spawned=list(TRENT);spawned[5]=1;spawned[7]=1700009110
self.time+=40;tick.OnUpdate();self.service.Reply([spawned,SKIPIA],time=1700000150)
self.assertEqual(self.chat,['TreeKing 已在 RedWood 刷新']);self.assertEqual(self.ns['g_tracker'].reminders,set())
def test_errors_and_close(self):
w=self.open();self.service.Reply([],error='unsupported');self.assertIn('未启用',w.status.text)
w.Query();self.service.Reply([]);self.assertIn('没有定时刷新',w.status.text)
w.Query();self.service.Reply([TRENT]);w.remindButtons[0].event()
self.game.GameWindow.Close(self.gw)
self.assertIsNone(self.ns['g_window']);self.assertIsNone(self.ns['g_entry'])
self.assertEqual(self.ns['g_tracker'].reminders,set());self.assertIsNone(self.ns['g_tracker'].rows)
def test_maps_match_server_index(self):
maps=self.ns['MAPS']
self.assertEqual((maps[68],maps[72],maps[302]),('metin2_map_trent02','metin2_map_skipia_dungeon_01','metin2_map_dawnmistwood'))
if __name__=='__main__':unittest.main()
+133
View File
@@ -0,0 +1,133 @@
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 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
NAMES={50100:'Box',27001:'Potion',110000:'Soul',30000:'Ore'}
TYPES={50100:23,27001:3,30000:5}
class ChestTests(unittest.TestCase):
def setUp(self):
self.time=1.;self.sent=[];self.chat=[];self.used=[];self.ctrl=False;self.bag={}
mods={n:types.ModuleType(n) for n in ('app','chat','game','grp','item','net','player','ui','uiInventory','mt_biolog','mt_wiki')}
app=mods['app'];app.GetTime=lambda:self.time;app.DIK_LCONTROL=29;app.DIK_RCONTROL=157
app.IsPressed=lambda key:self.ctrl and key==29
mods['chat'].CHAT_TYPE_INFO=1;mods['chat'].AppendChat=lambda t,m:self.chat.append(m)
mods['net'].SendChatPacket=self.sent.append
selected=[0];it=mods['item']
it.ITEM_TYPE_GIFTBOX=23;it.SelectItem=lambda v:selected.__setitem__(0,v)
it.GetItemName=lambda:NAMES.get(selected[0],'?');it.GetItemType=lambda:TYPES.get(selected[0],0)
pl=mods['player'];pl.INVENTORY_PAGE_SIZE=45;pl.INVENTORY_PAGE_COUNT=5
pl.GetItemIndex=lambda c:self.bag.get(c,(0,0))[0]
pl.GetItemCountByVnum=lambda v:sum(n for vnum,n in self.bag.values() if vnum==v)
mods['game'].GameWindow=type('GameWindow',(),dict(Open=lambda s:None,Close=lambda s:None,
BINARY_ServerCommand_Run=lambda s,line:7))
mods['uiInventory'].InventoryWindow=type('InventoryWindow',(),dict(UseItemSlot=lambda s,slot:self.used.append(slot),
_InventoryWindow__InventoryLocalSlotPosToGlobalSlotPos=lambda s,slot:slot+45))
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
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_chest'};exec(script('ChestScript.inc'),self.ns)
self.opener=self.ns['Opener'](self.sent.append,lambda:self.time)
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 test_open_sends_once_and_collects_gains_until_done(self):
self.assertTrue(self.opener.Open(50,7));self.assertFalse(self.opener.Open(50,7))
self.assertEqual(self.sent,['/mt_chest 1 open 50 7'])
self.time+=1;self.assertFalse(self.opener.Open(50,7)) # still waiting for the reply
for line in ('MTCH1 got 27001 7','MTCH1 got 110000 2','MTCH1 done 50100 7 7 done 700'):
self.assertTrue(self.opener.Receive(line))
r=self.opener.result
self.assertEqual((r['vnum'],r['asked'],r['opened'],r['reason'],r['gold']),(50100,7,7,'done',700))
self.assertEqual(r['gains'],[(27001,7),(110000,2)]);self.assertEqual(self.opener.gains,[])
self.assertTrue(self.opener.Open(50,500));self.assertEqual(self.sent[-1],'/mt_chest 1 open 50 200') # capped
self.opener.Receive('MTCH1 done 50100 200 0 rejected -50');self.assertEqual(self.opener.result['gold'],-50)
self.time+=.1;self.assertFalse(self.opener.Open(50,1)) # inside the send gap
def test_errors_malformed_and_foreign_lines(self):
self.opener.Open(1,1);self.opener.Receive('MTCH1 error kind')
self.assertEqual(self.opener.error,'kind');self.assertIsNone(self.opener.waiting)
for bad in ('MTCH1 done 1 1 1 done','MTCH1 done 1 1 1 boom 0','MTCH1 got x 1','MTCH1 got 1 0','MTCH1 error boom','MTCH1 done a 1 1 done 0'):
self.assertTrue(self.opener.Receive(bad))
self.assertEqual(self.opener.error,'kind');self.assertIsNone(self.opener.result)
self.assertFalse(self.opener.Receive('MTPU1 done 1 1 0'))
def test_timeout_marks_unsupported(self):
events=[];self.opener.listener=events.append
self.opener.Open(1,1);self.time+=3.1;self.assertFalse(self.opener.Open(1,1))
self.assertTrue(self.opener.unsupported);self.assertEqual(events,['unsupported'])
self.opener.Receive('MTCH1 done 50100 1 1 done 0');self.assertFalse(self.opener.unsupported) # a late reply re-enables
def test_summary_lines(self):
lines=self.ns['Summary'](dict(vnum=50100,opened=12,reason='full',gold=1200,gains=[(27001,12)]+[(30000,1)]*5))
self.assertEqual(lines[0],'批量开启 Box:开启 12 个,金币 +1200(背包空位不足,已停止)')
self.assertEqual(lines[1],'获得:Potion ×12,Ore ×1,Ore ×1,Ore ×1,Ore ×1');self.assertEqual(lines[2],'获得:Ore ×1')
self.assertEqual(self.ns['Summary'](dict(vnum=50100,opened=1,reason='done',gold=0,gains=[])),['批量开启 Box:开启 1 个'])
def test_ctrl_right_click_opens_window_and_hooks(self):
game=sys.modules['game'];inv=sys.modules['uiInventory'].InventoryWindow();gw=game.GameWindow()
self.bag={50:(50100,1),51:(50100,1),52:(27001,3),90:(50100,1)}
game.GameWindow.Open(gw);w=self.ns['g_window']
inv.UseItemSlot(5);self.assertEqual(self.used,[5]);self.assertFalse(w.IsShow()) # no Ctrl: original use
self.ctrl=True;inv.UseItemSlot(7);self.assertEqual(self.used,[5,7]) # Ctrl on a potion: original use
inv.UseItemSlot(5);self.assertEqual(self.used,[5,7]);self.assertTrue(w.IsShow())
self.assertEqual((w.cell,w.vnum),(50,50100));self.assertIn('3',w.owned.text);self.assertEqual(w.openButton.text,'开启 1 个')
w.allButton.event();self.assertEqual(w.openButton.text,'开启 3 个')
del self.bag[50];w.openButton.event();self.assertEqual(self.sent,['/mt_chest 1 open 51 2']) # chosen cell gone: next box, 2 left
self.assertFalse(w.openButton.enabled)
self.assertEqual(game.GameWindow.BINARY_ServerCommand_Run(gw,'MTCH1 got 27001 2'),1)
self.bag={52:(27001,6)}
self.assertEqual(game.GameWindow.BINARY_ServerCommand_Run(gw,'MTCH1 done 50100 2 2 done 200'),1)
self.assertEqual(self.chat,['批量开启 Box:开启 2 个,金币 +200','获得:Potion ×2'])
self.assertIn('2/2',w.status.text);self.assertEqual(w.openButton.text,'没有宝箱')
self.assertEqual(game.GameWindow.BINARY_ServerCommand_Run(gw,'other'),7)
self.bag={60:(50100,1)};self.time+=1;w.openButton.event();self.time+=3.1;w.OnUpdate()
self.assertTrue(self.ns['g_opener'].unsupported);self.assertIn('单个开启',self.chat[-1])
inv.UseItemSlot(15);self.assertEqual(self.used,[5,7,15]) # unsupported server: Ctrl falls back to normal use
game.GameWindow.Close(gw);self.assertIsNone(self.ns['g_window'])
def test_server_constants_match(self):
server=ROOT.parent/'metin2-server/src/server/game/src/port_chest.h'
if not server.exists():self.skipTest('server checkout not installed')
text=server.read_text(encoding='latin1')
self.assertIn('kPortChestMax=200',text);self.assertEqual(self.ns['MAX'],200)
self.assertIn('kPortChestGapMs=500',text);self.assertEqual(self.ns['SEND_GAP'],.5)
self.assertTrue(set(re.findall(r'return "([a-z]+)";',text))<=set(self.ns['ERRORS']))
self.assertTrue(set(re.findall(r'reason="([a-z]+)"',text))<=set(self.ns['REASONS']))
if __name__=='__main__':unittest.main()
+21
View File
@@ -110,6 +110,27 @@ class ServiceTests(unittest.TestCase):
self.assertEqual(self.replies[-1][1],expected)
if expected is None:self.assertEqual(self.replies[-1][0]['rows'][0][1],1)
def test_boss_rows_signed_positions_and_unsupported_on_old_cap(self):
self.s.mask=511
rid=self.request('bosses',0)
self.assertEqual(self.sent[-1],'/mt_features 1 %d bosses'%rid)
self.s.Receive('MTF1 begin %d bosses 0 0 2 0 1700000000'%rid)
self.s.Receive('MTF1 boss %d 0 2307 68 51200 -300 1 1 1 1700000900 9000'%rid)
self.s.Receive('MTF1 boss %d 1 2191 125 0 0 99 0 1 0 1800'%rid)
self.s.Receive('MTF1 end %d 2'%rid)
self.assertIsNone(self.replies[-1][1])
self.assertEqual(self.replies[-1][0]['rows'],[[2307,68,51200,-300,1,1,1,1700000900,9000],[2191,125,0,0,99,0,1,0,1800]])
for bad in ('2307 68 0 0 1 2 1 0 9000','0 68 0 0 1 0 1 0 9000','2307 68 0 0 1 0 1 0 0','2307 68 0 0 256 0 1 0 9000','2307 68 0 0 1 0 1 0'):
rid=self.request('bosses',0)
self.s.Receive('MTF1 begin %d bosses 0 0 1 0 1700000000'%rid)
self.s.Receive('MTF1 boss %d 0 %s'%(rid,bad));self.s.Receive('MTF1 end %d 1'%rid)
self.assertEqual(self.replies[-1],(None,'bad_reply'),bad)
self.assertEqual(self.s.Request('bosses',1,0,lambda d,e:self.replies.append((d,e))),0)
self.assertEqual(self.replies[-1],(None,'invalid'))
self.s.mask=255 # a server deployed before boss tracking
self.s.Request('bosses',0,0,lambda d,e:self.replies.append((d,e)));self.time+=1;self.s.Tick()
self.assertEqual(self.replies[-1],(None,'unsupported'))
def test_future_capability_bits_do_not_disable_known_features(self):
self.s.Request('stats',0,0,lambda d,e:None)
self.time+=1;self.s.Tick();rid=self.s.pending['id']
+30 -1
View File
@@ -118,11 +118,40 @@ class SwitchbotTests(unittest.TestCase):
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']))
lock_errors={'slot','max','db'}
self.assertTrue(reasons-{'invalid','running','item','equipped','no_attr','scroll','target','busy'}-lock_errors<=set(self.ns['REASONS']))
self.assertTrue(lock_errors<=set(self.ns['ERRORS']))
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_lock_protocol_and_buttons(self):
self.bot.Lock(10,0);self.assertEqual(self.sent,[]) # no lock line yet: old server, no request
self.load(self.bot);self.bot.Receive('MTSB1 lock 10 11209 2')
self.assertEqual(self.bot.LockMask(10,11209),2);self.assertIsNone(self.bot.LockMask(10,11210))
self.bot.Lock(10,5);self.bot.Lock(10,0);self.advance()
self.assertEqual(self.sent[-1],'/mt_switchbot 1 lock 10 0')
self.bot.Receive('MTSB1 lock 10 11209 3');self.assertIsNone(self.bot.waiting);self.assertEqual(self.bot.LockMask(10,11209),3)
self.bot.Lock(10,1);self.advance();self.bot.Receive('MTSB1 error lock max');self.assertEqual(self.bot.error,'max')
for bad in ('MTSB1 lock 10 11209','MTSB1 lock 10 11209 32'):self.bot.Receive(bad)
self.assertEqual(self.bot.LockMask(10,11209),3)
# Window: one button per filled slot, hidden while picking, locked attributes marked.
game=sys.modules['game'];gw=game.GameWindow();gw.interface=types.SimpleNamespace(wndMiniMap=Widget())
game.GameWindow.Open(gw);w=self.ns['g_window'];w.Open()
self.assertFalse(any(b.shown for b in w.lockButtons))
self.load(w.bot);w.bot.Receive('MTSB1 lock 10 11209 2')
self.assertEqual([b.shown for b in w.lockButtons],[True,True,False,False,False])
self.assertEqual([b.text for b in w.lockButtons[:2]],['锁1','【锁2】']);self.assertIn('[锁]',w.current.text.split(' / ')[1])
self.assertIn('保持不变',w.status.text)
self.time+=.5;w.OnUpdate();w.bot.Receive('MTSB1 state 0 0 0 0 0 0 0 idle') # answers the status request
sent=len(self.sent);w.lockButtons[0].event();self.time+=.5;w.OnUpdate()
self.assertEqual(self.sent[sent:],['/mt_switchbot 1 lock 10 0'])
w.TogglePick();self.assertFalse(any(b.shown for b in w.lockButtons));w.TogglePick()
w.bot.Receive('MTSB1 state 1 10 11209 0 100 71084 9 running');self.assertFalse(w.lockButtons[0].enabled)
sent=len(self.sent);w.lockButtons[0].event();self.time+=.5;w.OnUpdate()
self.assertNotIn('/mt_switchbot 1 lock 10 0',self.sent[sent:])
game.GameWindow.Close(gw)
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())