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>
This commit is contained in:
shenlei
2026-10-15 23:31:03 +09:00
co-authored by Claude Opus 5.5
parent 10f8c9760e
commit b8363693f1
7 changed files with 403 additions and 0 deletions
+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";
+2
View File
@@ -1001,6 +1001,7 @@ namespace PythonBoot
#include "WikiEntryScript.inc"
#include "SwitchbotScript.inc"
#include "PickupScript.inc"
#include "ChestScript.inc"
#include "DisplayScript.inc"
#include "ChannelScript.inc"
#include "BossScript.inc"
@@ -1079,6 +1080,7 @@ 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);
+2
View File
@@ -326,6 +326,8 @@ if(BUILD_TESTING AND CMAKE_SYSTEM_NAME STREQUAL CMAKE_HOST_SYSTEM_NAME)
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);