工具切换,食谱切换 区分 减少合并占用内存,箭桶有bug

This commit is contained in:
wenhe committed 2026-08-05 16:36:30 +08:00
1 parent 737b3f09ea
commit e8a22d8cb3
4 files changed
+616 -269

No files matched your search

@@ -12,6 +12,15 @@
玩家右键烹饪方块 → 引擎查 RecipeData 有没有匹配的配方 →
有就消耗手上物品 → 替换方块/记录翻炒进度 → 完成做菜
【为什么和工具切换分开】
原本做菜和普通工具方块切换(箭桶、水槽、书架、药水架等)都在这个类里。
现在已拆成两个独立系统:
- CookingService → 只处理做菜配方(RECIPES),本文件
- BlockSwitchService → 只处理工具方块切换(BLOCK_SWITCHES)
两个系统都监听同一个 ServerBlockUseEvent,
各自在事件第一行用 cookBlockSet/switchBlockSet(O(1) 的 set)按方块名拦截,
不是自己的方块直接 return,互不干扰,各自只查自己那一份数据。
【设计原则】
- 加新菜不改代码:在 RecipeData.py 加一条配方就行,这里一行不用动
- 所有做菜逻辑一处维护:炒锅、煎锅、油锅、架锅、蒸笼……全走同一个引擎
@@ -49,11 +58,6 @@ blockEntityDataComp = comp.CreateBlockEntityData(LevelId)
# RECIPES 是一个列表,每条配方是一个 dict,格式见 RecipeData.py 顶部注释
from ..RecipeData import RECIPES, inferBaseBlock, BELOW_CAMPFIRE
# ---- 导入工具方块切换规则 ----
# BLOCK_SWITCHES 是一个列表,每条规则是一个 dict,格式见 BlockSwitchData.py 顶部注释
from ..BlockSwitchData import BLOCK_SWITCHES
# ================================================================================
# 工具函数:读取物品 userData 里的嵌套字段
# ================================================================================
@@ -111,14 +115,8 @@ class CookingService(BlueFoxServerSystem):
2. 方块实体数据(blockEntityData)—— 慢一点,但关服重启后还在
每次操作都会同步更新两处,保证重启不丢进度
【工具方块记录数据】
switchRecord = {
(维度ID, x, y, z): {
"count": 整数, # recordType="count" 时记录数量(如箭桶里有多少箭)
"itemName": 字符串, # recordType="count" 时记录物品名(如"minecraft:arrow")
"stack": [物品信息列表], # recordType="stack" 时记录后进先出的物品堆
}
}
工具方块(箭桶、书架、药水架等)的记录数据已拆分到 BlockSwitchService,
本类只负责做菜配方(RECIPES)。
"""
def __init__(self, namespace, systemName):
@@ -128,22 +126,24 @@ class CookingService(BlueFoxServerSystem):
super(CookingService, self).__init__(namespace, systemName)
print "===== CookingService init ====="
self.stirData = {} # 内存中的翻炒数据字典
self.switchRecord = {} # 工具方块的记录数据(箭桶数量、药水架顺序等)
self.switchCooldown = {} # 工具方块切换冷却时间(防止连点)
self._cancelItemUse = {} # 将要取消下一次物品使用的玩家ID集合(防止喝药水等)
self.ListenEvent() # 注册游戏事件监听
# ---- 构建统一配方字典(O(1) 查找) ----
# 把 RECIPES(做菜配方)和 BLOCK_SWITCHES(工具切换规则)合并成一份字典
# ---- 构建做菜配方字典(O(1) 查找) ----
# 只含 RECIPES(做菜配方),工具方块切换已拆到 BlockSwitchService
# key = (方块名, 物品名),value = 配方dict
# 这样查找时不用遍历整个列表,直接 dict[key] 就能拿到,速度飞快
self.allRecipes = {}
for recipe in RECIPES:
key = (recipe["source"], recipe.get("item"))
self.allRecipes[key] = recipe
for switch in BLOCK_SWITCHES:
key = (switch["source"], switch.get("item"))
self.allRecipes[key] = switch
# ---- 构建做菜方块名集合(O(1) 快速拦截,第一道过滤) ----
# 事件进来先判断方块名在不在这个集合里,不在直接 return,
# 这样工具方块的右键事件根本不会进到本系统的字典查找
self.cookBlockSet = set()
for recipe in RECIPES:
self.cookBlockSet.add(recipe["source"])
def Destroy(self):
"""
@@ -200,10 +200,11 @@ class CookingService(BlueFoxServerSystem):
流程:
1. 拿到被右键的方块名、玩家ID、方块坐标
2. 看玩家手里拿了什么物品
3. 拿着"方块名+手里物品名"去统一字典里 O(1) 查找
4. 找到规则后,判断是"做菜配方"还是"工具切换"类型
5. 执行对应的逻辑
2. 先按方块名判断是不是本系统管辖的做菜方块(O(1) set 拦截)
- 不是 → 直接 return(这是工具方块的右键,交给 BlockSwitchService 处理)
3. 看玩家手里拿了什么物品
4. 拿着"方块名+手里物品名"去做菜字典里 O(1) 查找
5. 命中配方 → 查底座 → 执行做菜逻辑(翻炒/替换)
args 是网易API传过来的事件参数,包含:
- blockName: 被右键的方块名字(如 "rtdd:wok")
@@ -218,15 +219,20 @@ class CookingService(BlueFoxServerSystem):
dim = comp.CreateDimension(playerId).GetEntityDimensionId() # 玩家在哪个维度(主世界/下界/末地)
key = (dim, x, y, z) # 完整的唯一标识:维度+坐标
# ---- 第二步:拿到玩家手里拿的物品 ----
# ---- 第二步:O(1) 方块名拦截 ----
# 只有做菜方块的右键才归本系统处理;工具方块直接放过,交给 BlockSwitchService
if blockName not in self.cookBlockSet:
return
# ---- 第三步:拿到玩家手里拿的物品 ----
itemDict = self.getCarriedItem(playerId)
# itemDict 可能是 None(空手),也可能是 dict(手里有东西)
# dict 格式:{"newItemName": "rtdd:spatula", "count": 1, "userData": {...}}
# ---- 第三步:查配方(O(1) 字典查找) ----
# ---- 第四步:查做菜配方(O(1) 字典查找) ----
recipe = self.findRecipe(blockName, itemDict)
if not recipe:
# 没找到匹配的配方 → 不是做菜操作,不拦截,让游戏正常处理
# 方块是烹饪方块,但当前组合没有匹配的配方(比如手里物品不对)→ 不拦截
return
# 找到配方后,取消默认行为(如喝药水、吃食物等),由本 Mod 全权接管
@@ -234,26 +240,15 @@ class CookingService(BlueFoxServerSystem):
# 同时标记该玩家下一次物品使用事件也要取消,防止喝药水等默认行为
self._cancelItemUse[playerId] = True
# ---- 第四步:判断是不是工具切换类型 ----
recipeType = recipe.get("type", "cook")
# type="switch" 或 "timer" → 工具方块切换(箭桶、挂肉钩、水槽等)
# 没有 type 或 type="cook" → 做菜配方(炒锅、煎锅等)
# ---- 统一加载:把方块里的历史数据恢复到内存 ----
# 不管是做菜还是工具切换,先把方块数据加载到内存,后面直接用
# ---- 第五步:加载翻炒历史数据到内存 ----
# 这样 handleStir 里直接从 self.stirData 取就行
self._loadBlockDataToMemory(key, playerId, pos, dim, recipe)
if recipeType == "switch" or recipeType == "timer":
# 工具方块切换(水槽、箭桶、挂肉钩、盘子架等)不做底座检查,直接执行
self.handleSwitch(recipe, playerId, pos, dim, itemDict, key, blockName)
return
# ---- 底座检查:仅做菜配方才需要,锅下面必须有灶台/营火 ----
# 工具切换类型在上面已提前返回,不会走到这里
# ---- 底座检查:锅下面必须有灶台/营火 ----
if not self.checkBaseBlock(recipe, playerId, pos, dim):
return
# ---- 第五步:以下为做菜配方逻辑 ----
# ---- 第六步:以下为做菜配方逻辑 ----
# 内存中已有数据(_loadBlockDataToMemory 已加载),直接用
stirInfo = self.stirData.get(key, {})
@@ -315,152 +310,6 @@ class CookingService(BlueFoxServerSystem):
return None
# ============================================================================
# 工具方块切换处理
# ============================================================================
def handleSwitch(self, recipe, playerId, pos, dim, itemDict, key, blockName):
"""
处理工具方块的切换逻辑(箭桶、挂肉钩、水槽、盘子架、药水架、书柜等)。
支持三种模式:
1. recordType="count" → 记录一种物品+数量(如箭桶存箭)
2. recordType="stack" → 后进先出堆栈(如药水架、书柜)
3. 无 record → 纯切换,不记录(如挂肉钩直接换状态)
流程:
1. 如果是计时型(type="timer"),直接替换方块,不消耗物品
2. 如果是切换型(type="switch"),根据 recordType 决定记录方式
3. 消耗物品、替换方块、更新记录
"""
# ---- 如果规则指定了 tool,检查玩家手里是不是拿着指定工具 ----
if recipe.get("tool"):
if not itemDict:
return
carriedItem = itemDict.get("newItemName", "")
# 简单判断:物品名是否包含工具名
if recipe["tool"] not in carriedItem:
return
# ---- 冷却检查:防止连点右键瞬间切换多次 ----
now = time.time()
lastOp = self.switchCooldown.get(key, 0)
cd = recipe.get("switchCd", 0.5)
if now - lastOp < cd:
return
self.switchCooldown[key] = now
# ---- 计时型:直接替换方块,不消耗物品,不记录 ----
if recipe.get("type") == "timer":
if recipe.get("target"):
self.replaceBlock(pos, dim, recipe["target"], playerId)
return
# ---- 切换型 ----
# 内存中已有数据(_loadBlockDataToMemory 已加载),直接用
record = self.switchRecord.get(key)
# ---- 正向操作:往方块里放东西(source == 被右键的方块) ----
if recipe["source"] == blockName and recipe.get("item") is not None:
# 玩家手里有物品,往方块里放
needSave = False # 标记是否需要保存记录到方块
if recipe.get("record"):
if recipe.get("recordType") == "count":
# 数量记录型:只记录一种物品的总数
if not record:
record = {
"count": 0,
"itemName": itemDict["newItemName"],
}
# 检查是否满了
maxCount = recipe.get("maxCount", 999)
if record["count"] >= maxCount:
return
# 记录物品+1
record["count"] += 1
needSave = True
elif recipe.get("recordType") == "stack":
# 堆栈记录型:后进先出,记录每种物品的完整信息
if not record:
record = {"stack": []}
maxCount = recipe.get("maxCount", 999)
if len(record["stack"]) >= maxCount:
return
# 把物品信息压入堆栈
record["stack"].append({
"itemName": itemDict["newItemName"],
"count": itemDict.get("count", 1),
"auxValue": itemDict.get("newAuxValue", 0),
"userData": itemDict.get("userData", {}),
})
needSave = True
# 消耗物品
if recipe.get("consume", 1) > 0:
self.consumeItem(playerId, itemDict, recipe.get("consume", 1))
# 替换方块(旧方块销毁,新方块出现)
if recipe.get("target"):
self.replaceBlock(pos, dim, recipe["target"], playerId)
# ★ 关键:替换完方块后再保存记录到新方块上,否则数据随旧方块一起销毁
if needSave:
self._saveRecord(key, playerId, pos, dim, record)
# 如果配方指定了给物品(如烧烤架浇水给桶)
if recipe.get("giveItem"):
self.giveItem(playerId, recipe["giveItem"])
return
# ---- 逆向操作:从方块里取东西(空手右键或取回物品) ----
if recipe["source"] == blockName and recipe.get("item") is None:
needSaveRecord = False # 是否需要保存记录
needClearRecord = False # 是否需要清除记录
if recipe.get("record") and record:
if recipe.get("recordType") == "count":
# 数量记录型取回:给玩家对应的物品,数量-1
if record["count"] > 0:
self.giveItem(playerId, record["itemName"])
record["count"] -= 1
if record["count"] <= 0:
needClearRecord = True
else:
needSaveRecord = True
elif recipe.get("recordType") == "stack":
# 堆栈记录型取回:后进先出,取最后一个放的物品
if record["stack"]:
topItem = record["stack"].pop()
comp.CreateItem(playerId).SpawnItemToPlayerInv(
{"itemName": topItem["itemName"],
"count": topItem["count"],
"auxValue": topItem["auxValue"],
"userData": topItem.get("userData", {})},
playerId)
if not record["stack"]:
needClearRecord = True
else:
needSaveRecord = True
# 如果配方直接指定了给什么物品(水槽、盘子架取回、挂肉钩退回等)
if recipe.get("giveItem"):
self.giveItem(playerId, recipe["giveItem"])
# 替换方块(旧方块销毁,新方块出现)
if recipe.get("target"):
self.replaceBlock(pos, dim, recipe["target"], playerId)
# ★ 关键:替换完方块后再保存/清除记录,否则数据随旧方块一起销毁
if needClearRecord:
self.clearSwitchRecord(key, playerId, pos, dim)
elif needSaveRecord:
self._saveRecord(key, playerId, pos, dim, record)
return
# ============================================================================
# 配方执行(普通替换类型)
# ============================================================================
@@ -810,38 +659,20 @@ class CookingService(BlueFoxServerSystem):
except Exception as e:
print "[CookingService] _writeBlockData 写入失败: pos=%s dim=%s err=%s" % (pos, dim, str(e))
def _saveRecord(self, key, playerId, pos, dim, record):
"""
同时更新内存和方块实体数据中的工具方块记录。
替代原本重复出现的:
self.switchRecord[key] = record
self.saveSwitchRecord(playerId, pos, dim, record)
"""
self.switchRecord[key] = record
self.saveSwitchRecord(playerId, pos, dim, record)
# ============================================================================
# 统一数据加载入口(玩家右键方块时先把方块数据恢复到内存)
# ============================================================================
def _loadBlockDataToMemory(self, key, playerId, pos, dim, recipe):
"""
在确定玩家右键命中了一个配方后,立刻把方块里存的历史数据加载到内存。
在确定玩家右键命中了一个做菜配方后,立刻把方块里存的翻炒进度加载到内存。
这样 handleStir / handleSwitch 里就不用各自加载了,
直接从 self.stirData / self.switchRecord 取就行。
两个数据源互不干扰:翻炒数据用 stirData,工具切换记录用 switchRecord。
这样 handleStir 里就不用自己加载了,直接从 self.stirData 取就行。
"""
if key not in self.stirData:
stirInfo = self.loadStirData(playerId, pos, dim, recipe)
if stirInfo:
self.stirData[key] = stirInfo
if key not in self.switchRecord:
switchInfo = self.loadSwitchRecord(playerId, pos, dim)
if switchInfo:
self.switchRecord[key] = switchInfo
# ============================================================================
# 翻炒数据持久化(存方块里,不存JSON文件)
@@ -894,55 +725,6 @@ class CookingService(BlueFoxServerSystem):
self.stirData.pop(key, None)
self._writeBlockData(dim, pos, rtdd_sc=0, rtdd_slt=0.0, rtdd_sf=False)
# ============================================================================
# 工具方块记录持久化(药水架、书柜、箭桶等)
# ============================================================================
def saveSwitchRecord(self, playerId, pos, dim, record):
"""
把工具方块的记录数据写入方块实体数据。
记录类型:count型(箭桶)→ rtdd_swt/swc/swi,stack型(书柜/药水架)→ rtdd_swt/sws
"""
if "count" in record:
self._writeBlockData(dim, pos,
rtdd_swt="count",
rtdd_swc=record["count"],
rtdd_swi=record.get("itemName", ""))
elif "stack" in record:
self._writeBlockData(dim, pos,
rtdd_swt="stack",
rtdd_sws=record["stack"])
def loadSwitchRecord(self, playerId, pos, dim):
"""
从方块实体数据里读取工具方块的记录数据。
返回:
有数据 → {"count": N, "itemName": "xxx"} 或 {"stack": [...]}
没有 → None
"""
try:
blockData = blockEntityDataComp.GetBlockEntityData(dim, pos)
swt = blockData["rtdd_swt"] # 记录类型:"count" 或 "stack"
if swt == "count":
return {
"count": blockData["rtdd_swc"],
"itemName": blockData["rtdd_swi"],
}
elif swt == "stack":
return {
"stack": blockData["rtdd_sws"],
}
except:
return None
def clearSwitchRecord(self, key, playerId, pos, dim):
"""
清除工具方块的记录数据(内存+方块实体数据)。
"""
self.switchRecord.pop(key, None)
self._writeBlockData(dim, pos, rtdd_swt="", rtdd_swc=0, rtdd_swi="", rtdd_sws=[])
# ============================================================================
# 拆方块处理
# ============================================================================