Add switchbot (自动洗练) window for the server mt_switchbot command

Embedded module mt_switchbot: a paced request queue (0.3 s gap, one in
flight, 4 s timeout -> unsupported), atomic attrs lists from the server,
two alternatives of up to 5 targets, 10-1000 roll limits, live state and
stop reasons. Entry button under the wiki button by the minimap. The
selection follows the server-reported cell when the item moves mid-run
and falls back to the same vnum when it moves while idle.

Live tested against 203 (channel-5 test core, port 13040) with the macOS
native client.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shenlei
2026-10-15 19:45:14 +09:00
co-authored by Claude Opus 5.5
parent 4e2d39b612
commit 6b1d21a2c5
6 changed files with 585 additions and 0 deletions
+371
View File
@@ -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";