Files
metin2-client/tests/wiki/test_switchbot.py
T
shenleiandClaude Opus 5.5 fc98e6e2b4 Port the AVA2 switchbot window and switchbot module
PythonSwitchbot + PythonNetworkStreamPhaseGameSwitchbot from AVA2 (CG/GC 171,
SWITCHBOT window 7, SLOT_TYPE_SWITCHBOT), uiswitchbot.py verbatim in
SwitchbotScript.inc plus its ENABLE_SWITCHBOT glue (tooltip, mouse/inventory
drag-back, interface/game hooks, zh strings, server switchbot_* messages).
Entry is the minimap 洗练 button; F9 stays with auto-hunt. The client version
timestamp is now "mt20261016" so the server enables the switchbot.
50348/50349 no longer open the window. Adds docs/AVA2-PARITY-PLAN.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 20:26:06 +09:00

134 lines
8.3 KiB
Python

"""mt_switchbot (SwitchbotScript.inc): AVA2 root/uiswitchbot.py verbatim plus its ENABLE_SWITCHBOT glue. The window
talks to the C++ switchbot module (CG/GC_SWITCHBOT 171), items move through the SWITCHBOT window, and the server
reports end/stop/error as switchbot_* commands. The old /mt_switchbot chat protocol is gone."""
import sys
import types
import unittest
from pathlib import Path
ROOT=Path(__file__).resolve().parents[2]
AVA2=ROOT.parent/'AVA2/TEST/1. Client DEV/pack_maker/root/uiswitchbot.py'
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);self.itemList=[]
def __getattr__(self,name):
if name.startswith('__'):raise AttributeError(name)
return lambda *a,**k:0
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 GetText(self):return self.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.text=text;self.event=event;self.shown=True
class Mouse(object):
def __init__(self):self.AttachedFlag=False;self.AttachedType=0;self.AttachedSlotNumber=0;self.AttachedCount=0;self.AttachedIconHandle=0
def AttachObject(self,owner,kind,slot,vnum,count=0):
self.AttachedFlag=True;self.AttachedType=kind;self.AttachedSlotNumber=slot;self.AttachedCount=count;self.AttachedIconHandle=9
def DeattachObject(self):self.AttachedFlag=False;self.AttachedIconHandle=0
def isAttached(self):return self.AttachedFlag
def GetAttachedType(self):return self.AttachedType
def GetAttachedSlotNumber(self):return self.AttachedSlotNumber
def GetAttachedItemCount(self):return self.AttachedCount
class SwitchbotTests(unittest.TestCase):
def setUp(self):
self.moves=[];self.chat=[];self.icons=[];self.deleted=[];self.passed=[];self.bag={(7,2):11209}
names=('dbg','constInfo','app','ime','item','grp','net','ui','uiToolTip','player','mouseModule','localeInfo','wndMgr',
'cPickle','switchbot','chat','game','interfaceModule','uiInventory','mt_biolog')
mods={n:types.ModuleType(n) for n in names};self.mods=mods
mods['constInfo'].GET_ITEM_QUESTION_DIALOG_STATUS=lambda:0
mods['grp'].GenerateColor=lambda *a:0
it=mods['item'];it.APPLY_SKILL_DAMAGE_BONUS=71;it.APPLY_NORMAL_HIT_DAMAGE_BONUS=72;self.selected=0
it.SelectItem=lambda v:setattr(self,'selected',v);it.GetItemName=lambda:'N%d'%self.selected;it.GetItemSize=lambda:(1,2)
it.DeleteIconInstance=self.deleted.append
mods['net'].SendItemMovePacket=lambda *a:self.moves.append(a)
ui=mods['ui']
for n in ('Window','Bar','BoardWithTitleBar','Box','Button','EditLine','ExpandedImageBox','GridSlotWindow','ListBoxEx',
'RadioButton','ScrollBar','TextLine'):setattr(ui,n,type(n,(Widget,),{}))
ui.__mem_func__=lambda f:f
mods['uiToolTip'].ItemToolTip=type('ItemToolTip',(),dict(AFFECT_DICT={}))
pl=mods['player'];pl.INVENTORY=1;pl.SWITCHBOT=7;pl.SLOT_TYPE_INVENTORY=1;pl.SLOT_TYPE_SWITCHBOT=33
pl.AutoHuntLocalize=lambda t:t;pl.GetItemIndex=lambda w,c:self.bag.get((w,c),0)
mods['mouseModule'].CMouseController=Mouse;self.mouse=mods['mouseModule'].mouseController=Mouse()
mods['wndMgr'].AttachIcon=lambda *a:self.icons.append(a)
sb=mods['switchbot'];sb.SLOT_COUNT=5;sb.ALTERNATIVE_COUNT=2
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,
BINARY_ServerCommand_Run=lambda s,line:self.passed.append(line) or 7))
mods['interfaceModule'].Interface=type('Interface',(),dict(HideAllWindows=lambda s:None,_Interface__HideWindows=lambda s:[]))
mods['uiInventory'].InventoryWindow=type('InventoryWindow',(),dict(SelectEmptySlot=lambda s,c:self.passed.append(('empty',c)),
_InventoryWindow__InventoryLocalSlotPosToGlobalSlotPos=lambda s,c:c+45))
mods['mt_biolog'].Action=Action
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)
def tearDown(self):
for n,value in self.previous.items():
if value is None:sys.modules.pop(n,None)
else:sys.modules[n]=value
def test_verbatim_ava2_window(self):
text=script('SwitchbotScript.inc')
for name in ('SwitchbotItemTab(ui.ThinBoardCircle)','SwitchbotAttribute(ui.Window)','SwitchbotWindow(ui.BoardWithTitleBar)',
'SearchListWindow(ui.BoardWithTitleBar)','ConfigurationWindow(ui.BoardWithTitleBar)'):
self.assertIn('class %s:'%name,text)
self.assertNotIn('/mt_switchbot',text);self.assertNotIn('SendChatPacket',text)
if not AVA2.is_file():self.skipTest('AVA2 tree not checked out')
src=AVA2.read_bytes().decode('latin1').replace('\r\n','\n');src=src[src.index('COLOR_INACTIVE'):].rstrip()
src=src.replace('self.alternativeTextLine.SetText("Alternativen:")','self.alternativeTextLine.SetText(localeInfo.SWITCHBOT_ALTERNATIVES)')
body=text[text.index('COLOR_INACTIVE'):text.index('# --- uitooltip.py')].rstrip()
body=body.replace('\t# PORT: AVA2 left this German','').replace(
'attrTab.Hide()\t# PORT: switchers stay in the inventory, cell 5 is unused (server port_switchbot.cpp)','attrTab.Show()')
self.assertEqual(body,src)
def test_ui_and_locale_parts(self):
self.assertIs(self.mods['ui'].ThinBoardCircle,self.ns['ThinBoardCircle'])
box=self.mods['ui'].ListBoxEx();box.itemList=[1,2];self.assertEqual(box.GetItems(),[1,2])
self.assertEqual(self.mods['localeInfo'].SWITCHBOT_TITLE,'自动洗练')
self.assertEqual(self.mods['constInfo'].USERDATA_DIRECTORY,'')
self.assertEqual(self.ns['ITEM_TAB_WIDTH'],(400-16)/5+1-2) # 5 tabs: cell 5 is hidden, as in AVA2
def test_server_messages(self):
game=self.mods['game'].GameWindow()
for line in ('switchbot_end 2','switchbot_stop noattr 1','switchbot_stop nochanger 0','switchbot_error active',
'switchbot_error invalid','switchbot_end x','quest 3'):
game.BINARY_ServerCommand_Run(line)
self.assertEqual(self.chat,['N11209(第 3 格)洗练完成!','第 2 格的物品没有可洗练的属性,已停止。',
'自动洗练已停止:背包里没有可用的洗练道具。','该格正在洗练,请先停止。','这件物品不能自动洗练。'])
self.assertEqual(self.passed,['quest 3'])
def test_drag_back_to_inventory(self):
self.mouse.AttachObject(None,self.mods['player'].SLOT_TYPE_SWITCHBOT,2,11209,1)
self.assertEqual(self.mouse.AttachedType,33);self.assertEqual(self.icons,[(33,11209,2,1,2)])
self.mods['uiInventory'].InventoryWindow().SelectEmptySlot(4)
self.assertEqual(self.moves,[(7,2,1,49,1)]);self.assertFalse(self.mouse.isAttached());self.assertEqual(self.deleted,[9])
self.mods['uiInventory'].InventoryWindow().SelectEmptySlot(5);self.assertEqual(self.passed,[('empty',5)])
def test_interface_hooks(self):
Interface=self.mods['interfaceModule'].Interface;ui=Interface()
ui.RefreshSwitchbotWindow();ui.ToggleSwitchbotWindow() # no window yet: no-ops
calls=[]
ui.wndSwitchbot=types.SimpleNamespace(shown=True,IsShow=lambda:True,Hide=lambda:calls.append('hide'),
RefreshSwitchbotWindow=lambda:calls.append('refresh'),RefreshSwitchbotItem=lambda s:calls.append(('item',s)),Close=lambda:calls.append('close'))
game=self.mods['game'].GameWindow();game.interface=ui
game.RefreshSwitchbotWindow();game.RefreshSwitchbotItem(3);ui.ToggleSwitchbotWindow()
self.assertEqual(ui._Interface__HideWindows(),[ui.wndSwitchbot]);ui.HideAllWindows()
self.assertEqual(calls,['refresh',('item',3),'close','hide','hide'])
if __name__=='__main__':unittest.main()