feat: port native AVA2 chest preview and CG235 pickup flows

This commit is contained in:
shen
2026-10-18 04:01:56 -07:00
parent b61140b8f4
commit 83809631ed
24 changed files with 872 additions and 614 deletions
@@ -0,0 +1,25 @@
// PORT: AVA2 ui.py additions shared by native feature windows; keep base scripts unchanged.
static const char c_szAva2UICompatScript[] = R"PY(# -*- coding: utf-8 -*-
import ui
# AVA2 Button.SetListText / PythonScriptLoader.LoadElementButton text_x branch.
def SetListText(self,text,x=8):
if not self.ButtonText:
textLine=ui.TextLine()
textLine.SetParent(self)
textLine.Show()
self.ButtonText=textLine
self.ButtonText.SetPosition(x,self.GetHeight()/2)
self.ButtonText.SetVerticalAlignCenter()
self.ButtonText.SetHorizontalAlignLeft()
self.ButtonText.SetWindowHorizontalAlignLeft()
self.ButtonText.SetText(text)
ui.Button.SetListText=SetListText
_loadButton=ui.PythonScriptLoader.LoadElementButton
def LoadElementButton(self,window,value,parent):
result=_loadButton(self,window,value,parent)
if 'text' in value and 'text_x' in value and 'text_height' not in value:
window.SetListText(value['text'],value['text_x'])
return result
ui.PythonScriptLoader.LoadElementButton=LoadElementButton
)PY";
+262 -190
View File
@@ -1,219 +1,291 @@
// 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.
// PORT: AVA2 uichestdropinfo.py with stale-cell and slider bounds fixes; original UIScript packed in ava2items.
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
import game
import uiInventory
import uiScriptLocale
import item
import player
import net
import ui
L=player.AutoHuntLocalize
uiScriptLocale.CHEST_DROP_TITLE=L('宝箱奖励预览')
uiScriptLocale.CHEST_DROP_OPEN=L('开启')
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':'宝箱无法开启,已停止'}
#blackdragonx61 (28.11.21)
import ui
import item
import uiToolTip
import player
import net
class ChestDropInfoWindow(ui.ScriptWindow):
DROP_SLOT_SIZE = 5 * 8
ITEM = 0
COUNT = 1
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
def __init__(self) :
ui.ScriptWindow.__init__(self)
self.isLoaded = False
self.ItemVnum = -1
self.PageCount = 0
self.CurrentPage = 0
self.DropDict = dict()
self.MainItemSlot = None
self.DropItemSlot = None
self.prevButton = None
self.nextButton = None
self.currentPageText = None
self.tooltipitem = None
self.itemCell = [-1, -1]
self.itemCount = 0
def __del__(self) :
ui.ScriptWindow.__del__(self)
self.DropDict = None
self.MainItemSlot = None
self.DropItemSlot = None
self.prevButton = None
self.nextButton = None
self.currentPageText = None
self.tooltipitem = None
self.itemCell = 0
self.itemCount = 0
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 __LoadWindow(self):
if self.isLoaded:
return
def Busy(self):return self.waiting is not None or self.now()<self.nextSend
self.isLoaded = True
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
# script
try:
self.__LoadScript("UIScript/ChestDropInfoWindow.py")
except:
import exception
exception.Abort("ChestDropInfoWindow.__LoadWindow.__LoadScript")
def Tick(self):
if self.waiting is not None and self.now()>=self.waiting:
self.waiting=None;self.unsupported=True;self.Notify('unsupported')
# object
try:
self.__BindObject()
except:
import exception
exception.Abort("ChestDropInfoWindow.__LoadWindow.__BindObject")
def Notify(self,kind):
if self.listener:self.listener(kind)
# event
try:
self.__BindEvent()
except:
import exception
exception.Abort("ChestDropInfoWindow.__LoadWindow.__BindEvent")
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 __LoadScript(self, fileName):
pyScrLoader = ui.PythonScriptLoader()
pyScrLoader.LoadScriptFile(self, fileName)
def __BindObject(self):
self.MainItemSlot = self.GetChild("main_item_slot")
self.DropItemSlot = self.GetChild("drop_item_slot")
self.prevButton = self.GetChild("prev_button")
self.nextButton = self.GetChild("next_button")
self.currentPageText = self.GetChild("CurrentPage")
def ItemName(vnum):
item.SelectItem(vnum);return item.GetItemName()
def __BindEvent(self):
self.GetChild("board").SetCloseEvent(ui.__mem_func__(self.Close))
self.MainItemSlot.SetOverInItemEvent(ui.__mem_func__(self.OverInMainItemSlot))
self.MainItemSlot.SetOverOutItemEvent(ui.__mem_func__(self.OverOutItem))
self.GetChild("open_btn").SetEvent(ui.__mem_func__(self.ClickOpenMultiChest))
self.GetChild("count_controller").SetEvent(ui.__mem_func__(self.OnChangeCount))
self.DropItemSlot.SetOverInItemEvent(ui.__mem_func__(self.OverInDropItemSlot))
self.DropItemSlot.SetOverOutItemEvent(ui.__mem_func__(self.OverOutItem))
self.prevButton.SetEvent(ui.__mem_func__(self.SetPage), -1)
self.nextButton.SetEvent(ui.__mem_func__(self.SetPage), +1)
def UpdateItems(self):
for i in range(ChestDropInfoWindow.DROP_SLOT_SIZE):
self.DropItemSlot.ClearSlot(i)
if self.CurrentPage in self.DropDict:
for pos in self.DropDict[self.CurrentPage]:
data = self.DropDict[self.CurrentPage][pos]
self.DropItemSlot.SetItemSlot(pos, data[ChestDropInfoWindow.ITEM], data[ChestDropInfoWindow.COUNT])
self.DropItemSlot.RefreshSlot()
def ClickOpenMultiChest(self):
if player.GetItemIndex(*self.itemCell) != self.ItemVnum:
self.Close()
return
owned = min(player.GetItemCount(*self.itemCell), 1000)
if owned <= 0:
self.Close()
return
realpos = max(1, min(owned, int(self.GetChild("count_controller").GetSliderPos()*self.itemCount)))
net.SendChatPacket("/chest_drop %d %d %d"%(self.itemCell[0], self.itemCell[1],realpos))
self.Close()
def OnChangeCount(self):
if self.itemCount <= 0: return
realpos = max(1,min(self.itemCount,int(self.GetChild("count_controller").GetSliderPos()*self.itemCount)))
self.GetChild("countSliderText").SetText("%d/%d"%(int(realpos),self.itemCount))
def UpdateCountSlider(self, itemWindow, itemCell):
if itemCell == -1:
return
self.itemCell = [itemWindow, itemCell]
self.itemCount = min(1000, player.GetItemCount(*self.itemCell))
slider = self.GetChild("count_controller")
sliderText = self.GetChild("countSliderText")
if self.itemCount <= 0:
slider.Hide()
sliderText.Hide()
self.GetChild("open_btn").Hide()
return
else:
self.GetChild("open_btn").Show()
slider.Show()
sliderText.Show()
value =1.0/float(self.itemCount)
pos = value*1.0
slider.SetSliderPos(pos)
sliderText.SetText("1/%d"%self.itemCount)
def SetTooltipItem(self, tooltipItem):
self.tooltipitem = tooltipItem
def SetPage(self, page):
nextpage = page + self.CurrentPage
if 0 <= nextpage <= self.PageCount:
self.CurrentPage = nextpage
self.currentPageText.SetText(str(self.CurrentPage + 1))
self.UpdateItems()
def SetUp(self, itemVnum):
self.ItemVnum = itemVnum
self.MainItemSlot.SetItemSlot(0, self.ItemVnum, 0)
self.MainItemSlot.RefreshSlot()
(self.PageCount, DropList) = item.GetDropInfo(self.ItemVnum)
self.DropDict.clear()
for i in range(self.PageCount + 1):
self.DropDict[i] = dict()
for page, pos, vnum, count in DropList:
self.DropDict[page][pos] = (vnum, count)
self.CurrentPage = 0
self.SetPage(0)
def Open(self, itemVnum, itemWindow, itemCell):
#if self.IsShow():
# return
self.__LoadWindow()
self.SetUp(itemVnum)
self.UpdateCountSlider(itemWindow, itemCell)
self.SetCenterPosition()
self.SetTop()
self.Show()
def OverInMainItemSlot(self, slotIndex):
if self.tooltipitem:
self.tooltipitem.SetItemToolTip(self.ItemVnum)
def OverInDropItemSlot(self, slotIndex):
if self.tooltipitem:
if self.CurrentPage in self.DropDict:
if slotIndex in self.DropDict[self.CurrentPage]:
data = self.DropDict[self.CurrentPage][slotIndex]
self.tooltipitem.SetItemToolTip(data[ChestDropInfoWindow.ITEM])
def OverOutItem(self):
if self.tooltipitem:
self.tooltipitem.HideToolTip()
self.tooltipitem.ClearToolTip()
def Close(self):
self.OverOutItem()
self.Hide()
def OnPressEscapeKey(self):
self.Close()
return True
def Batchable(vnum):
if not vnum:return False
item.SelectItem(vnum);return item.GetItemType()==GIFTBOX
if not vnum: return False
item.SelectItem(vnum)
return item.GetItemType()==item.ITEM_TYPE_GIFTBOX
def Select(self,cell,vnum):
self.Open(vnum,player.INVENTORY,cell)
ChestDropInfoWindow.Select=Select
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
g_window=None
_oldOpen=game.GameWindow.Open
_oldClose=game.GameWindow.Close
_oldCommand=game.GameWindow.BINARY_ServerCommand_Run
_oldUse=uiInventory.InventoryWindow._InventoryWindow__UseItem
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):
def GameOpen(self):
global g_window
_open(self);g_opener.waiting=None;g_window=ChestWindow(g_opener)
_oldOpen(self)
item.ClearDropInfo()
g_window=ChestDropInfoWindow()
g_window.SetTooltipItem(self.interface.tooltipItem)
def Close(self):
def GameClose(self):
global g_window
if g_window:g_window.Destroy();g_window=None
_close(self)
if g_window:
g_window.Close()
g_window.ClearDictionary()
g_window=None
item.ClearDropInfo()
_oldClose(self)
def UseItem(self,cell):
vnum=player.GetItemIndex(player.INVENTORY,cell)
item.SelectItem(vnum)
if (g_window and item.GetItemType()==item.ITEM_TYPE_GIFTBOX and
not item.IsFlag(item.ITEM_FLAG_CONFIRM_WHEN_USE) and
(app.IsPressed(app.DIK_LCONTROL) or app.IsPressed(app.DIK_RCONTROL))):
if app.IsPressed(app.DIK_Z):
net.SendChatPacket('/chest_drop %d %d %d'%(player.INVENTORY,cell,min(1000,player.GetItemCount(player.INVENTORY,cell))))
else:
g_window.Open(vnum,player.INVENTORY,cell)
return
return _oldUse(self,cell)
def OpenChestDrop(self,vnum):
# A late catalogue response must never replace another box or reopen a closed window.
if g_window and g_window.IsShow() and g_window.ItemVnum==vnum:
g_window.SetUp(vnum)
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
words=line.split()
if words and words[0] in ('chest_reward','chest_opened','chest_error'):
if words[0]=='chest_reward' and len(words)==3 and all(x.isdigit() for x in words[1:]):
item.SelectItem(int(words[1]))
chat.AppendChat(chat.CHAT_TYPE_INFO,L('获得:%s ×%s'%(B(item.GetItemName()),words[2])))
elif words[0]=='chest_opened' and len(words)==2 and words[1].isdigit():
chat.AppendChat(chat.CHAT_TYPE_INFO,L('背包空间不足,已开启 %s 个宝箱'%words[1]))
elif words[0]=='chest_error':
chat.AppendChat(chat.CHAT_TYPE_INFO,L('宝箱无法开启或背包空间不足。'))
return 1
return _oldCommand(self,line)
game.GameWindow.BINARY_ServerCommand_Run=Command
uiInventory.InventoryWindow.UseItemSlot=UseItemSlot
game.GameWindow.Open=GameOpen
game.GameWindow.Close=GameClose
game.GameWindow.OpenChestDrop=OpenChestDrop
uiInventory.InventoryWindow._InventoryWindow__UseItem=UseItem
)PY";
+96 -180
View File
@@ -1,194 +1,110 @@
// PORT: AVA2-style batch pickup (do_pickup_all), driven by the server's /mt_pickup command. With batch
// pickup on, the pickup key (GameWindow.PickUpItem, Z / `) asks the server to pick up every own item in
// range of the chosen categories; each item still goes through the original pickup path. Against a server
// without the command it falls back to the original single pickup. Protocol: metin2-server docs/FEATURE-PICKUP.md.
// PORT: AVA2 CG235 pickup and original game_option_0_1.py panel.
static const char c_szPickupScript[] = R"PY(# -*- coding: utf-8 -*-
import app
import chat
import game
import grp
import net
import ui
import weakref
from mt_biolog import Action, Text, L
from mt_wiki import B
import app, chat, constInfo, game, net, player, ui, uiScriptLocale, uiAffectShower
L=player.AutoHuntLocalize
uiAffectShower.AffectShower.AFFECT_DATA_DICT[705]=(lambda value:L("第三只手"),"d:/ymir work/ui/game/farm/premium_pickup.tga")
constInfo.PICKUPMODE=0
constInfo.RARITYMODE=0
constInfo.PREMIUMMODE=[False,0]
NAMES=('weapons','armors','shield','ring','helmets','bracelets','necklace','earrings','costume','petnmount','sash','talisman','books','stones','yang','chests','foots','belt')
LABELS=('武器','铠甲','盾牌','戒指','头盔','手镯','项链','耳环','时装','宠物坐骑','肩带','护符','技能书','灵石','金币','宝箱','鞋子','腰带')
KEYS=('WEAPONS','ARMORS','SHIELD','RING','HELMETS','BRACELETS','NECKLACE','EARRINGS','COSTUME','PETNMOUNT','SASH','TALISMAN','BOOKS','STONES','YANG','CHESTS','SHOES','BELT')
for key,label in zip(KEYS,LABELS):setattr(uiScriptLocale,'AUTOMATIC_PCIK_UP_'+key,L(label))
for key,text in {'AUTOMATIC_PCIK_UP_ACTIVATE':'开启','AUTOMATIC_PCIK_UP_DEACTIVATE':'关闭',
'AUTOMATIC_PICKUP_TEXT_0':'第三只手','AUTOMATIC_PICKUP_TEXT_1':'未激活',
'AUTOMATIC_PICKUP_TEXT_3':'使用第三只手可激活 30 天',
'AUTOMATIC_PICKUP_TEXT_4':'勾选下方分类后,将忽略该类物品。',
'AUTOMATIC_PICKUP_TEXT_5':'按 Z 或拾取按钮批量拾取。',
'AUTOMATIC_PICK_UP':'批量拾取','AUTOMATIC_PICK_UP_FILTER':'忽略物品分类',
'AUTOMATIC_PICK_UP_FILTER_RARITY':'稀有度过滤','AUTOMATIC_RARITY_INFO':'稀有度系统尚未开放'}.items():setattr(uiScriptLocale,key,L(text))
for key,label in zip(('NORMAL','UNCOMMUN','RARE','EPIC','RELIC','LEGENDARY'),('普通','优秀','稀有','史诗','遗物','传说')):
setattr(uiScriptLocale,'AUTOMATIC_RARITY_'+key,L(label))
class PickupWindow(ui.BoardWithTitleBar):
def __init__(self):
ui.BoardWithTitleBar.__init__(self)
self.SetSize(320,470);self.SetTitleName(L('拾取设置'));self.AddFlag('movable');self.AddFlag('float')
self.SetCloseEvent(self.Hide)
self.panel=ui.ScriptWindow();self.panel.SetParent(self)
ui.PythonScriptLoader().LoadScriptFile(self.panel,'UIScript/game_option_0_1.py')
self.panel.SetPosition(10,35);self.panel.Show()
self.filters=[]
for index,name in enumerate(NAMES):
button=self.panel.GetChild('pick_up_'+name)
button.SetToggleUpEvent(lambda bit=1<<(index+1):self.SetIgnore(bit,False))
button.SetToggleDownEvent(lambda bit=1<<(index+1):self.SetIgnore(bit,True))
self.filters.append(button)
self.activate=[self.panel.GetChild('pick_up_button_activate'),self.panel.GetChild('pick_up_button_deactivate')]
for button in self.activate:
button.SetToggleUpEvent(self.Toggle);button.SetToggleDownEvent(self.Toggle)
# These controls belong to the not-yet-ported rarity item system.
for name in ('normal','uncommun','rare','epic','relic','legendary'):
self.panel.GetChild('rarity_'+name).Disable()
self.Hide()
def SetIgnore(self,bit,ignore):
mode=(constInfo.PICKUPMODE|bit) if ignore else (constInfo.PICKUPMODE&~bit)
net.SendChatPacket('/setpickupmode %u %u'%(mode,constInfo.RARITYMODE))
def Toggle(self):net.SendChatPacket('/setpickupmode %u %u'%(constInfo.PICKUPMODE^1,constInfo.RARITYMODE))
def Refresh(self):
for i,button in enumerate(self.filters):
if constInfo.PICKUPMODE&(1<<(i+1)):button.Down()
else:button.SetUp()
for i,button in enumerate(self.activate):
if bool(constInfo.PICKUPMODE&1)==(i==0):button.Down()
else:button.SetUp()
active=constInfo.PREMIUMMODE[0] and constInfo.PREMIUMMODE[1]>app.GetGlobalTimeStamp()
self.panel.GetChild('pickup_premimum_image').LoadImage('d:/ymir work/ui/game/gameoption/pickup/'+('activated.tga' if active else 'not_activated.tga'))
seconds=max(0,constInfo.PREMIUMMODE[1]-app.GetGlobalTimeStamp())
self.panel.GetChild('pickup_premium_text_1').SetText(L('剩余 %d 天 %d 小时'%(seconds//86400,(seconds%86400)//3600) if active else '未激活'))
def Open(self):
self.Refresh();self.SetCenterPosition();self.Show();self.SetTop()
net.SendChatPacket('/setpickupmode')
def OnPressEscapeKey(self):self.Hide();return True
g_window=None
g_entry=None
CONFIG='mt_pickup.cfg'
ALL=255
CATEGORIES=((1,u'金币'),(2,u'武器'),(4,u'防具/首饰'),(8,u'技能书'),(16,u'灵石'),(32,u'材料'),(64,u'时装'),(128,u'其他'))
SEND_GAP=.5
TIMEOUT=3.
ERRORS={'rate':'操作过快','invalid':'参数无效','busy':'当前状态不能拾取'}
def Number(text,low=0,high=4294967295):
if not text.isdigit() or len(text)>10:raise ValueError(text)
value=int(text)
if not low<=value<=high:raise ValueError(text)
return value
class Picker(object):
# Protocol state only. send(text) posts a chat command, now() is seconds.
def __init__(self,send,now,listener=None):
self.send=send;self.now=now;self.listener=listener
self.enabled=True;self.mask=ALL;self.waiting=None;self.nextSend=0
self.unsupported=False;self.result=None;self.error=None
def Press(self):
# True when the press was handled here; False means use the original single pickup.
self.Tick()
if not self.enabled or self.unsupported:return False
now=self.now()
if self.waiting is None and now>=self.nextSend:
self.send('/mt_pickup 1 %d'%self.mask);self.waiting=now+TIMEOUT;self.nextSend=now+SEND_GAP
return True
def Tick(self):
if self.waiting is not None and self.now()>=self.waiting:
self.waiting=None;self.unsupported=True;self.Notify('unsupported')
def Notify(self,kind):
if self.listener:self.listener(kind)
def Receive(self,line):
if not line.startswith('MTPU1 '):return False
words=line.split()
try:
if words[1]=='done' and len(words)==5:
found,picked,failed=[Number(w,0,1000) for w in words[2:]]
self.result=dict(found=found,picked=picked,failed=failed);self.error=None;kind='done'
elif words[1]=='error' and len(words)==3 and words[2] in ERRORS:self.error=words[2];kind='error'
else:return True
except ValueError:return True
self.waiting=None;self.unsupported=False;self.Notify(kind)
return True
def Load(self,text):
try:
enabled,mask=[Number(w) for w in text.split()]
if enabled in (0,1) and 1<=mask<=ALL:self.enabled=enabled==1;self.mask=mask
except ValueError:pass
def Dump(self):return '%d %d'%(int(self.enabled),self.mask)
def Toggle(self,bit):
mask=self.mask^bit
if mask:self.mask=mask # at least one category stays on
def LoadConfig(picker):
try:
f=open(CONFIG,'r');text=f.read();f.close();picker.Load(text)
except (IOError,OSError):pass
def SaveConfig(picker):
try:
f=open(CONFIG,'w');f.write(picker.Dump());f.close()
except (IOError,OSError):pass
class PickupWindow(ui.Window):
def __init__(self,picker):
ui.Window.__init__(self);self.SetWindowName('PickupWindow');self.AddFlag('float');self.AddFlag('movable')
self.picker=picker;self.SetSize(332,346)
self.heading=Text(self,18,18,'批量拾取',0xffffd68b)
self.closeButton=Action(self,256,6,60,'关闭',self.Hide)
self.enableButton=Action(self,18,52,296,'',self.ToggleEnabled)
self.categoryButtons=[Action(self,18+(i%2)*152,108+(i//2)*52,144,'',lambda bit=bit:self.ToggleCategory(bit))
for i,(bit,name) in enumerate(CATEGORIES)]
self.status=Text(self,18,322,'',0xffc3b7a1)
self.Refresh();self.Hide()
def Buttons(self):return [self.closeButton,self.enableButton]+self.categoryButtons
def Open(self):self.Refresh();self.SetCenterPosition();self.Show();self.SetTop()
def ToggleEnabled(self):
self.picker.enabled=not self.picker.enabled;self.picker.unsupported=False;SaveConfig(self.picker);self.Refresh()
def ToggleCategory(self,bit):self.picker.Toggle(bit);SaveConfig(self.picker);self.Refresh()
def Refresh(self):
p=self.picker
self.enableButton.SetText(L('拾取键(Z):批量拾取 已开启' if p.enabled else '拾取键(Z):批量拾取 已关闭(单个拾取)'))
for button,(bit,name) in zip(self.categoryButtons,CATEGORIES):
button.SetText(L(B(u'【%s】'%name if p.mask&bit else name)))
button.SetEnabled(p.enabled)
self.status.SetText(L(self.StatusText()))
def StatusText(self):
p=self.picker
if p.unsupported:return '!服务器尚未启用批量拾取,已改用单个拾取'
if p.error:return '!'+ERRORS[p.error]
if p.result:
r=p.result;text='上次:附近 %d 件,拾取 %d 件'%(r['found'],r['picked'])
return text+(',%d 件未能拾取'%r['failed'] if r['failed'] else '')
return '只拾取自己的物品,范围与单个拾取相同'
def OnRender(self):
x,y=self.GetGlobalPosition();grp.SetColor(0xf51b1916);grp.RenderBar(x,y,self.GetWidth(),self.GetHeight());grp.SetColor(0xff9b7b48);grp.RenderBox(x,y,self.GetWidth(),self.GetHeight())
def OnUpdate(self):self.picker.Tick()
def OnPressEscapeKey(self):self.Hide();return True
def Destroy(self):
self.Hide()
for b in self.Buttons():b.event=None
class Entry(Action):
def __init__(self,window):
Action.__init__(self,None,0,0,64,'拾取',Toggle)
self.minimap=weakref.proxy(window.interface.wndMiniMap);self.SetWindowName('PickupEntry');self.OnUpdate();self.Hide()
def OnUpdate(self):
x,y=self.minimap.GetGlobalPosition();self.SetPosition(max(4,x-68),y+200)
def OnPicker(kind):
if kind=='unsupported':chat.AppendChat(chat.CHAT_TYPE_INFO,L('服务器尚未启用批量拾取,已改用单个拾取'))
if g_window:g_window.Refresh()
g_picker=Picker(net.SendChatPacket,app.GetTime,OnPicker)
LoadConfig(g_picker)
def Toggle():
if g_window:
if g_window.IsShow():g_window.Hide()
else:g_window.Open()
_open=game.GameWindow.Open
_close=game.GameWindow.Close
_command=game.GameWindow.BINARY_ServerCommand_Run
_pick=game.GameWindow.PickUpItem
_oldOpen=game.GameWindow.Open
_oldClose=game.GameWindow.Close
_oldCommand=game.GameWindow.BINARY_ServerCommand_Run
_oldPick=game.GameWindow.PickUpItem
_oldAdd=game.GameWindow.BINARY_NEW_AddAffect
_oldRemove=game.GameWindow.BINARY_NEW_RemoveAffect
def Open(self):
global g_window,g_entry
_open(self);g_picker.waiting=None;g_window=PickupWindow(g_picker);g_entry=Entry(self)
global g_window
constInfo.PICKUPMODE=0;constInfo.RARITYMODE=0;constInfo.PREMIUMMODE=[False,0]
_oldOpen(self);g_window=PickupWindow()
net.SendChatPacket('/setpickupmode')
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)
global g_window
if g_window:
g_window.Hide();g_window.panel.ClearDictionary();g_window=None
_oldClose(self)
def Command(self,line):
if g_picker.Receive(line):return 1
return _command(self,line)
words=line.split()
if words and words[0]=='PickUPMode':
if len(words)==3 and all(w.isdigit() for w in words[1:]):
constInfo.PICKUPMODE=int(words[1])&((1<<19)-1);constInfo.RARITYMODE=int(words[2])&63
if g_window:g_window.Refresh()
return 1
return _oldCommand(self,line)
def PickUpItem(self):
if not g_picker.Press():_pick(self)
if constInfo.PICKUPMODE&1:player.PickCloseItemVector()
else:return _oldPick(self)
def AddAffect(self,kind,point,value,duration):
if kind==705:
constInfo.PREMIUMMODE=[True,app.GetGlobalTimeStamp()+int(duration)]
if g_window:g_window.Refresh()
return _oldAdd(self,kind,point,value,duration)
def RemoveAffect(self,kind,point):
if kind==705:
constInfo.PREMIUMMODE=[False,0]
if g_window:g_window.Refresh()
return _oldRemove(self,kind,point)
game.GameWindow.Open=Open
game.GameWindow.Close=Close
game.GameWindow.BINARY_ServerCommand_Run=Command
game.GameWindow.PickUpItem=PickUpItem
game.GameWindow.BINARY_NEW_AddAffect=AddAffect
game.GameWindow.BINARY_NEW_RemoveAffect=RemoveAffect
)PY";
+2
View File
@@ -1018,6 +1018,7 @@ namespace PythonBoot
#include "DungeonScript.inc"
#include "CalendarScript.inc"
#include "WikiEntryScript.inc"
#include "Ava2UICompatScript.inc"
#include "SwitchbotScript.inc"
#include "PickupScript.inc"
#include "ChestScript.inc"
@@ -1117,6 +1118,7 @@ bool RunMainScript(const char* lpCmdLine, std::string* error)
install_script_module("mt_dungeons", c_szDungeonScript);
install_script_module("mt_calendar", c_szCalendarScript);
install_script_module("mt_wiki_entries", c_szWikiEntryScript);
install_script_module("mt_ava2_ui", c_szAva2UICompatScript);
install_script_module("mt_switchbot", c_szSwitchbotScript);
install_script_module("mt_pickup", c_szPickupScript);
install_script_module("mt_chest", c_szChestScript);