烧烤 动物养殖 分类 功能实现1
This commit is contained in:
1 parent
98335837dd
commit
eac9409571
16 files changed
+1493
-5
No files matched your search
+332
@@ -0,0 +1,332 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
================================================================================
|
||||
动物养殖引擎(服务端)
|
||||
================================================================================
|
||||
只处理"动物养殖"(xy_animal) 分类下的方块转换:鸡窝、饲料盆、饲料槽、粪便。
|
||||
|
||||
【与 BlockSwitchService / CookingService 的区别】
|
||||
那些系统各自监听 ServerBlockUseEvent,右键时会互相跑一遍拦截。
|
||||
本系统(方案A)改为"统一分发器"架构:
|
||||
- FeatureDispatcher 是唯一监听 ServerBlockUseEvent 的系统
|
||||
- 本类通过 FeatureDispatcher.register(self) 把管辖的方块名注册进去
|
||||
- 玩家右键方块时,FeatureDispatcher 用 O(1) 的 dict 直接找到本实例
|
||||
- 本类只查自己的 AnimalData(ANIMAL_SWITCHES),不碰其他功能的数据库
|
||||
→ 每个右键事件只查一次数据库,功能损耗最小
|
||||
|
||||
【本类不做的事】
|
||||
- 不自己监听 ServerBlockUseEvent(由 FeatureDispatcher 统一转发 handleBlockUse)
|
||||
- 不处理其他分类的方块(数据只来自 AnimalData)
|
||||
|
||||
【转换类型】
|
||||
- type="switch" : 右键直接转换(放蛋/取蛋/填充饲料/清理粪便/加水)
|
||||
- type="timer" : 计时自动转换(饲料盆/饲料槽随时间变空),
|
||||
由本类用 AddTimer 实现,不依赖方块实体 tick
|
||||
================================================================================
|
||||
"""
|
||||
import time
|
||||
import mod.server.extraServerApi as serverApi
|
||||
|
||||
# ---- 网易API基础对象 ----
|
||||
ServerSystem = serverApi.GetServerSystemCls() # 服务端系统基类
|
||||
comp = serverApi.GetEngineCompFactory() # 组件工厂
|
||||
|
||||
# ---- 继承 BlueFox 框架的系统基类(提供 AddTimer / CreateEngineItemEntity 等方法) ----
|
||||
from ....BlueFoxTools.SpecialFunciton.BlueFoxSystem import BlueFoxServerSystem
|
||||
from ....BlueFoxTools.ToolsConfig import LevelId
|
||||
|
||||
# ---- 只导入动物养殖自己的数据库 ----
|
||||
from ..AnimalData import ANIMAL_SWITCHES
|
||||
|
||||
# ---- 统一分发器(本类把自己注册进去,让分发器把右键事件转发过来) ----
|
||||
from ...service.FeatureDispatcher import FeatureDispatcher
|
||||
|
||||
|
||||
class AnimalService(BlueFoxServerSystem):
|
||||
"""
|
||||
动物养殖引擎
|
||||
|
||||
【核心数据结构】
|
||||
animalRecipes = {
|
||||
(方块名, 物品名): 规则dict, # O(1) 查找
|
||||
}
|
||||
animalBlockSet = {方块名, ...} # O(1) 拦截/注册用
|
||||
animalTimers = {方块名: 规则dict} # 计时型规则的起始方块 → 规则
|
||||
"""
|
||||
|
||||
def __init__(self, namespace, systemName):
|
||||
"""
|
||||
初始化:构建自己的转换规则字典,并注册到统一分发器
|
||||
"""
|
||||
super(AnimalService, self).__init__(namespace, systemName)
|
||||
print "===== AnimalService init ====="
|
||||
|
||||
# ---- 构建动物养殖规则字典(O(1) 查找) ----
|
||||
self.animalRecipes = {}
|
||||
self.animalBlockSet = set()
|
||||
self.animalTimers = {}
|
||||
for sw in ANIMAL_SWITCHES:
|
||||
key = (sw["source"], sw.get("item"))
|
||||
self.animalRecipes[key] = sw
|
||||
self.animalBlockSet.add(sw["source"])
|
||||
# 收集计时型规则的"起始方块",方便转换后自动启动计时
|
||||
if sw.get("type") == "timer":
|
||||
self.animalTimers[sw["source"]] = sw
|
||||
|
||||
# ---- 计时去重表:key=(dim,x,y,z) -> 上次启动计时的时间戳 ----
|
||||
self._timerSchedule = {}
|
||||
|
||||
# ---- 右键冷却表:防止连点瞬间触发多次 ----
|
||||
self.cooldown = {}
|
||||
|
||||
# ---- 注册到统一分发器(把管辖方块交给 FeatureDispatcher 路由) ----
|
||||
FeatureDispatcher.register(self)
|
||||
|
||||
# ============================================================================
|
||||
# 给 FeatureDispatcher 的接口
|
||||
# ============================================================================
|
||||
|
||||
def getFeatureBlocks(self):
|
||||
"""
|
||||
返回本功能管辖的所有方块名集合。
|
||||
FeatureDispatcher 靠它构建 方块名→本实例 的 O(1) 路由表。
|
||||
"""
|
||||
return self.animalBlockSet
|
||||
|
||||
def getItemUseOnRules(self):
|
||||
"""
|
||||
返回本功能的"手持物品右键方块表面"规则(当前动物养殖没有,返回空)。
|
||||
接口统一预留,方便以后扩展(如手持鸡蛋右键地面直接生蛋等)。
|
||||
"""
|
||||
return {}
|
||||
|
||||
def handleBlockUse(self, args):
|
||||
"""
|
||||
由 FeatureDispatcher 转发的右键方块入口。
|
||||
只有 blockName 在本功能的方块集合里才会被调用。
|
||||
|
||||
返回 True = 本功能处理了这个右键(分发器会取消默认行为)
|
||||
返回 False = 当前组合没有匹配规则(分发器不拦截,交还默认行为)
|
||||
"""
|
||||
blockName = args.get("blockName")
|
||||
playerId = args.get("playerId")
|
||||
x, y, z = args.get("x"), args.get("y"), args.get("z")
|
||||
pos = (x, y, z)
|
||||
dim = comp.CreateDimension(playerId).GetEntityDimensionId()
|
||||
key = (dim, x, y, z)
|
||||
|
||||
# ---- 拿玩家主手物品 ----
|
||||
itemDict = self.getCarriedItem(playerId)
|
||||
|
||||
# ---- 查动物养殖规则(O(1)) ----
|
||||
recipe = self.findRecipe(blockName, itemDict)
|
||||
if not recipe:
|
||||
return False
|
||||
|
||||
# ---- 冷却检查(防止连点,规则可自定义冷却时间 switchCd) ----
|
||||
if not self.checkCooldown(key, recipe.get("switchCd", 0.5)):
|
||||
return True # 冷却中,虽然不执行但也算"处理了",避免默认行为
|
||||
|
||||
# ---- 计时型规则:启动/续计时,不立即转换 ----
|
||||
if recipe.get("type") == "timer":
|
||||
self.startTimer(key, recipe, dim, playerId)
|
||||
return True
|
||||
|
||||
# ---- 切换型规则:执行具体转换 ----
|
||||
self.handleSwitch(recipe, playerId, pos, dim, itemDict, key, blockName)
|
||||
return True
|
||||
|
||||
# ============================================================================
|
||||
# 规则匹配(O(1) 字典查找)
|
||||
# ============================================================================
|
||||
|
||||
def findRecipe(self, blockName, itemDict):
|
||||
"""
|
||||
在动物养殖字典中查找匹配规则:
|
||||
1. 先精确匹配 (方块名, 物品名)
|
||||
2. 没找到再匹配 (方块名, None) —— 空手也能触发的规则
|
||||
"""
|
||||
itemName = itemDict.get("newItemName") if itemDict else None
|
||||
recipe = self.animalRecipes.get((blockName, itemName))
|
||||
if recipe:
|
||||
return recipe
|
||||
recipe = self.animalRecipes.get((blockName, None))
|
||||
if recipe:
|
||||
return recipe
|
||||
return None
|
||||
|
||||
# ============================================================================
|
||||
# 切换型规则处理
|
||||
# ============================================================================
|
||||
|
||||
def handleSwitch(self, recipe, playerId, pos, dim, itemDict, key, blockName):
|
||||
"""
|
||||
处理"右键直接转换"类规则。
|
||||
|
||||
正向(item 不为 None):放蛋/加饲料/加水 → 消耗物品 → 替换方块 → 给奖励 → 续计时
|
||||
逆向(item 为 None) :取蛋/清理粪便/取回 → 掉落物品 → 替换方块
|
||||
"""
|
||||
# ---- 正向操作:往方块里放东西 ----
|
||||
if recipe.get("item") is not None:
|
||||
# 消耗物品
|
||||
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 recipe.get("giveItem"):
|
||||
self.giveItem(playerId, recipe["giveItem"], recipe.get("giveCount", 1))
|
||||
|
||||
# ★ 如果新方块是某个计时链的起始方块 → 自动启动计时(如刚装满的饲料盆)
|
||||
if recipe.get("target") in self.animalTimers:
|
||||
nextTimer = self.animalTimers[recipe["target"]]
|
||||
self.startTimer(key, nextTimer, dim, playerId)
|
||||
|
||||
return
|
||||
|
||||
# ---- 逆向操作:取东西/清理 ----
|
||||
# 掉落物形式生成(取蛋、取下物品等),优先于 giveItem
|
||||
if recipe.get("dropItem"):
|
||||
self.dropItems(dim, pos, recipe["dropItem"])
|
||||
elif recipe.get("giveItem"):
|
||||
self.giveItem(playerId, recipe["giveItem"], recipe.get("giveCount", 1))
|
||||
|
||||
# 替换方块(可能是空气=消失)
|
||||
if recipe.get("target"):
|
||||
self.replaceBlock(pos, dim, recipe["target"], playerId)
|
||||
|
||||
# ============================================================================
|
||||
# 计时型规则处理(AddTimer 一次性定时,不依赖方块实体tick)
|
||||
# ============================================================================
|
||||
|
||||
def startTimer(self, key, recipe, dim, playerId=None):
|
||||
"""
|
||||
为计时型规则启动一次性定时器。
|
||||
1 秒内的重复调用会被去重(防止多次右键重复计时)。
|
||||
到时间后由 _timerDone 检查方块状态并执行转换。
|
||||
"""
|
||||
now = time.time()
|
||||
last = self._timerSchedule.get(key, 0)
|
||||
if now - last < 1.0:
|
||||
return
|
||||
self._timerSchedule[key] = now
|
||||
|
||||
t = recipe.get("time", 60)
|
||||
# 用系统自带 AddTimer 一次性定时
|
||||
self.AddTimer(t, self._timerDone, key, recipe, dim)
|
||||
|
||||
def _timerDone(self, key, recipe, dim):
|
||||
"""
|
||||
定时器到点回调:
|
||||
检查当前方块是否仍是计时源方块(防止玩家中途改变了方块),
|
||||
是则替换为下一状态;若新状态仍是计时源则继续下一级计时。
|
||||
"""
|
||||
pos = (key[1], key[2], key[3])
|
||||
try:
|
||||
cur = comp.CreateBlockInfo(LevelId).GetBlockNew(pos, dim)
|
||||
if not cur or cur.get("name") != recipe["source"]:
|
||||
return # 方块已变,放弃本次转换
|
||||
# 替换方块
|
||||
self.replaceBlock(pos, dim, recipe["target"], None)
|
||||
# 若新方块仍是计时源 → 继续下一级计时(如 满→半→少→空)
|
||||
nextRecipe = self.animalTimers.get(recipe["target"])
|
||||
if nextRecipe:
|
||||
self.startTimer(key, nextRecipe, dim)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ============================================================================
|
||||
# 工具方法:获取玩家主手物品
|
||||
# ============================================================================
|
||||
|
||||
def getCarriedItem(self, playerId):
|
||||
itemComp = comp.CreateItem(playerId)
|
||||
return itemComp.GetPlayerItem(
|
||||
serverApi.GetMinecraftEnum().ItemPosType.CARRIED, 0)
|
||||
|
||||
# ============================================================================
|
||||
# 工具方法:消耗物品
|
||||
# ============================================================================
|
||||
|
||||
def consumeItem(self, playerId, itemDict, amount=1):
|
||||
if itemDict is None:
|
||||
return
|
||||
count = itemDict.get("count", 0)
|
||||
if count <= amount:
|
||||
comp.CreateItem(playerId).SetEntityItem(
|
||||
serverApi.GetMinecraftEnum().ItemPosType.CARRIED,
|
||||
{"itemName": "minecraft:air", "count": 0, "auxValue": 0})
|
||||
else:
|
||||
itemDict["count"] = count - amount
|
||||
comp.CreateItem(playerId).SetEntityItem(
|
||||
serverApi.GetMinecraftEnum().ItemPosType.CARRIED,
|
||||
{"itemName": itemDict["newItemName"],
|
||||
"count": itemDict["count"],
|
||||
"auxValue": itemDict.get("newAuxValue", 0)})
|
||||
|
||||
# ============================================================================
|
||||
# 工具方法:替换方块
|
||||
# ============================================================================
|
||||
|
||||
def replaceBlock(self, pos, dim, newBlockName, playerId, aux=None):
|
||||
"""
|
||||
替换指定位置的方块。
|
||||
newBlockName="minecraft:air" 表示清除该方块。
|
||||
playerId 可为 None(计时回调时没有玩家),用 LevelId 创建组件。
|
||||
"""
|
||||
creator = playerId if playerId is not None else LevelId
|
||||
if aux is None:
|
||||
try:
|
||||
oldBlock = comp.CreateBlockInfo(creator).GetBlockNew(pos, dim)
|
||||
aux = oldBlock.get("aux", 0)
|
||||
except Exception:
|
||||
aux = 0
|
||||
comp.CreateBlockInfo(creator).SetBlockNew(
|
||||
pos,
|
||||
blockDict={"name": newBlockName, "aux": aux},
|
||||
oldBlockHandling=0,
|
||||
dimensionId=dim)
|
||||
|
||||
# ============================================================================
|
||||
# 工具方法:给玩家物品(塞背包)
|
||||
# ============================================================================
|
||||
|
||||
def giveItem(self, playerId, itemName, count=1, auxValue=0):
|
||||
comp.CreateItem(playerId).SpawnItemToPlayerInv(
|
||||
{"itemName": itemName, "count": count, "auxValue": auxValue}, playerId)
|
||||
|
||||
# ============================================================================
|
||||
# 工具方法:以掉落物形式生成物品(取蛋/取下物品等,符合"获得"体验)
|
||||
# ============================================================================
|
||||
|
||||
def dropItems(self, dim, pos, dropList):
|
||||
"""
|
||||
dropList 格式:[{"name": "minecraft:egg", "count": 5}, ...]
|
||||
在方块上方生成掉落物实体,让它自然掉到地上。
|
||||
"""
|
||||
for d in dropList:
|
||||
itemDict = {
|
||||
"itemName": d["name"],
|
||||
"count": d.get("count", 1),
|
||||
"auxValue": d.get("aux", 0),
|
||||
}
|
||||
self.CreateEngineItemEntity(itemDict, dim, (pos[0], pos[1] + 0.5, pos[2]))
|
||||
|
||||
# ============================================================================
|
||||
# 工具方法:冷却检查
|
||||
# ============================================================================
|
||||
|
||||
def checkCooldown(self, key, cd=0.5):
|
||||
"""
|
||||
右键冷却:同一方块 cd 秒内只响应一次,防止连点刷物品。
|
||||
放蛋等需要快速连点的规则可在数据里用 switchCd 调小冷却。
|
||||
"""
|
||||
now = time.time()
|
||||
last = self.cooldown.get(key, 0)
|
||||
if now - last < cd:
|
||||
return False
|
||||
self.cooldown[key] = now
|
||||
return True
|
||||
Whitespace-only changes.
Reference in new issue
Block a user