NpcMgr NPC管理器(Lua 传奇MMO服务端)

职责:地图NPC实例生成、刷新/销毁、NPC对话脚本、商店打开、传送、任务交互、NPC临时刷新(活动NPC)、GM指令,和ShopMgr、QuestMgr联动。

约定:

  • 静态NPC:地图配置开局加载,常驻;
  • 动态NPC:活动/脚本临时刷出,带存活时长;
  • 不做战斗AI(战斗AI归MonsterMgr),Npc只管交互逻辑。

1. 配表 npc_cfg

ini 复制代码
-- ConfigMgr npc_cfg
{
    npc_id = 1001,
    name = "老兵",
    map_id = 1,
    x = 320,
    y = 330,
    dir = 2,
    type = 1, -- 1对话NPC 2商店NPC 3传送NPC 4任务NPC
    shop_id = 0, -- type=2时有效,ShopMgr商店ID
    talk_script = "npc_1001", -- 对话脚本key
    teleport_map = 0, -- type=3传送目标map
    teleport_x = 0,
    teleport_y = 0,
    quest_list = {2001,2002}, -- 可接任务列表
    is_static = 1, -- 1静态常驻 0动态临时
}

2. 内存结构

ini 复制代码
-- npc_inst_id 全局唯一实例id
-- g_NpcMap: map_id -> { [inst_id] = npcData }
local g_NpcMap = {}
-- g_NpcDict: inst_id -> npcData
local g_NpcDict = {}

npcData字段:

ini 复制代码
{
    inst_id = 100001,
    npc_cfg_id = 1001,
    map_id = 1,
    x = 320,
    y = 330,
    dir = 2,
    name = "老兵",
    type = 1,
    expire_ts = 0, -- 动态npc过期时间,0=永久静态
}

3. proto协议

ini 复制代码
// 点击NPC交互
message C2S_NpcInteract {
    int64 inst_id = 1;
}
message S2C_NpcDialog {
    string content = 1;
    repeated NpcOption option_list = 2;
}
message NpcOption {
    int32 opt_id = 1;
    string txt = 2;
}
// 选择对话选项
message C2S_NpcSelectOpt {
    int64 inst_id = 1;
    int32 opt_id = 2;
}
// 同步地图NPC列表(玩家进入地图推送)
message S2C_MapNpcList {
    repeated NpcSimpleItem list = 1;
}
message NpcSimpleItem {
    int64 inst_id = 1;
    int32 npc_cfg_id = 2;
    string name = 3;
    int32 x = 4;
    int32 y = 5;
    int32 dir = 6;
}

4. 错误码

ini 复制代码
local NpcErr = {
    OK = 0,
    NpcNotExist = -3101,
    NpcNotInMap = -3102,
    ScriptNotFind = -3103,
    TeleportForbid = -3104,
    ShopNotOpen = -3105,
    QuestNoAvailable = -3106,
}

5. NpcMgr 完整源码

lua 复制代码
local NpcMgr = {}
NpcMgr.__index = NpcMgr

local g_NpcMap = {}
local g_NpcDict = {}
local g_InstIdSeed = 100000
local g_NpcScript = {} -- 对话脚本注册表 key=scriptName

function NpcMgr:Init()
    -- 加载所有静态NPC
    local allNpcCfg = ConfigMgr:GetAllCfg("npc_cfg")
    for _,cfg in ipairs(allNpcCfg) do
        if cfg.is_static == 1 then
            self:SpawnNpc(cfg.npc_id, cfg.map_id, cfg.x, cfg.y, cfg.dir, 0)
        end
    end
    -- 定时清理过期动态NPC 10s扫描一次
    TimerMgr:AddTimer("NpcCleanExpire", 10, function()
        self:CleanExpireNpc()
    end)
end

-- 生成唯一实例ID
function NpcMgr:GenInstId()
    g_InstIdSeed = g_InstIdSeed + 1
    return g_InstIdSeed
end

-- 刷NPC
-- expireTs=0 静态永久;>0动态限时
function NpcMgr:SpawnNpc(npcCfgId, mapId, x, y, dir, expireTs)
    local cfg = ConfigMgr:GetCfg("npc_cfg", npcCfgId)
    if not cfg then
        return nil
    end
    local instId = self:GenInstId()
    local npcData = {
        inst_id = instId,
        npc_cfg_id = npcCfgId,
        map_id = mapId,
        x = x,
        y = y,
        dir = dir,
        name = cfg.name,
        type = cfg.type,
        cfg = cfg,
        expire_ts = expireTs or 0,
    }
    if not g_NpcMap[mapId] then
        g_NpcMap[mapId] = {}
    end
    g_NpcMap[mapId][instId] = npcData
    g_NpcDict[instId] = npcData
    -- 通知当前地图在线玩家刷新NPC
    SceneMgr:BroadcastMap(mapId, "S2C_AddMapNpc", {
        inst_id = instId,
        npc_cfg_id = npcCfgId,
        name = cfg.name,
        x = x,
        y = y,
        dir = dir
    })
    LogMgr:Info(string.format("NpcMgr Spawn inst=%d cfg=%d map=%d pos(%d,%d)", instId, npcCfgId, mapId, x, y))
    return npcData
end

-- 移除NPC
function NpcMgr:DespawnNpc(instId)
    local npc = g_NpcDict[instId]
    if not npc then return false end
    local mapId = npc.map_id
    g_NpcDict[instId] = nil
    if g_NpcMap[mapId] then
        g_NpcMap[mapId][instId] = nil
    end
    -- 地图广播删除
    SceneMgr:BroadcastMap(mapId, "S2C_RemoveMapNpc", {inst_id = instId})
    LogMgr:Info("NpcMgr Despawn inst="..instId)
    return true
end

-- 玩家进入地图,推送该地图所有NPC
function NpcMgr:SendMapNpcList(player, mapId)
    local list = {}
    local mapNpc = g_NpcMap[mapId] or {}
    for _,npc in pairs(mapNpc) do
        table.insert(list, {
            inst_id = npc.inst_id,
            npc_cfg_id = npc.npc_cfg_id,
            name = npc.name,
            x = npc.x,
            y = npc.y,
            dir = npc.dir
        })
    end
    MsgMgr:SendToPlayer(player, "S2C_MapNpcList", {list = list})
end

-- 注册对话脚本
function NpcMgr:RegScript(scriptKey, fn)
    g_NpcScript[scriptKey] = fn
end

-- 玩家点击NPC交互入口
function NpcMgr:InteractNpc(roleId, instId)
    local npc = g_NpcDict[instId]
    if not npc then
        return NpcErr.NpcNotExist
    end
    local player = PlayerMgr:GetPlayer(roleId)
    if not player then return NpcErr.NpcNotExist end
    -- 距离校验(和NPC过远不能交互)
    if not SceneMgr:CheckPosDistance(player:GetMapId(), player:GetPos(), npc.map_id, {x=npc.x,y=npc.y}, 4) then
        return NpcErr.NpcNotInMap
    end
    local cfg = npc.cfg
    -- 分支处理NPC类型
    if cfg.type == 2 then
        -- 商店NPC,打开商店
        ShopMgr:OpenShop(player, cfg.shop_id)
        return NpcErr.OK
    elseif cfg.type == 3 then
        -- 传送NPC
        local ok = SceneMgr:PlayerTeleport(player, cfg.teleport_map, cfg.teleport_x, cfg.teleport_y)
        return ok and NpcErr.OK or NpcErr.TeleportForbid
    elseif cfg.type == 4 then
        -- 任务NPC,走QuestMgr获取对话+选项
        local ret, dialog, optList = QuestMgr:GetNpcDialog(roleId, cfg.quest_list)
        if ret ~=0 then return ret end
        MsgMgr:SendToPlayer(player, "S2C_NpcDialog", {content=dialog, option_list=optList})
        return NpcErr.OK
    else
        -- 普通对话脚本NPC
        local scriptFn = g_NpcScript[cfg.talk_script]
        if not scriptFn then
            return NpcErr.ScriptNotFind
        end
        local content, optList = scriptFn(roleId, npc)
        MsgMgr:SendToPlayer(player, "S2C_NpcDialog", {content=content, option_list=optList})
        return NpcErr.OK
    end
end

-- 玩家选择对话选项
function NpcMgr:SelectOption(roleId, instId, optId)
    local npc = g_NpcDict[instId]
    if not npc then return NpcErr.NpcNotExist end
    local cfg = npc.cfg
    if cfg.type == 4 then
        -- 任务选项交给QuestMgr处理(接任务/交任务)
        local ret = QuestMgr:OnNpcSelectOpt(roleId, instId, optId)
        return ret
    end
    -- 普通脚本选项回调
    local scriptFn = g_NpcScript[cfg.talk_script]
    if not scriptFn then return NpcErr.ScriptNotFind end
    local ret = scriptFn:OnSelect(roleId, npc, optId)
    return ret
end

-- 定时清理过期动态NPC
function NpcMgr:CleanExpireNpc()
    local now = os.time()
    local delList = {}
    for instId,npc in pairs(g_NpcDict) do
        if npc.expire_ts >0 and npc.expire_ts < now then
            table.insert(delList, instId)
        end
    end
    for _,instId in ipairs(delList) do
        self:DespawnNpc(instId)
    end
end

return NpcMgr

6. 对话脚本注册示例(npc_1001老兵)

ini 复制代码
-- 脚本注册放在初始化阶段
NpcMgr:RegScript("npc_1001", function(roleId, npc)
    local player = PlayerMgr:GetPlayer(roleId)
    local lv = player:GetLevel()
    local content = string.format("年轻人,欢迎来到土城!你当前等级:%d", lv)
    local optList = {
        {opt_id=1, txt="我要去商店"},
        {opt_id=2, txt="传送去比奇"},
        {opt_id=3, txt="离开"},
    }
    return content, optList
end)
-- 选项回调扩展,可以在脚本内绑定跳转逻辑

7. MsgMgr消息注册

css 复制代码
MsgMgr:Register("C2S_NpcInteract", function(player, pkt)
    local ret = NpcMgr:InteractNpc(player:GetRoleId(), pkt.inst_id)
    MsgMgr:SendToPlayer(player, "S2C_Ret", {ret=ret})
end)
MsgMgr:Register("C2S_NpcSelectOpt", function(player, pkt)
    local ret = NpcMgr:SelectOption(player:GetRoleId(), pkt.inst_id, pkt.opt_id)
    MsgMgr:SendToPlayer(player, "S2C_Ret", {ret=ret})
end)

8. GM指令

lua 复制代码
-- 刷动态NPC,限时
GMMgr:RegisterCmd("npc_spawn", 2, function(player, args)
    local npcCfgId = tonumber(args[1])
    local mapId = tonumber(args[2]) or player:GetMapId()
    local x = tonumber(args[3]) or player:GetX()
    local y = tonumber(args[4]) or player:GetY()
    local liveSec = tonumber(args[5]) or 0 -- 0永久
    local expireTs = liveSec>0 and (os.time()+liveSec) or 0
    local npc = NpcMgr:SpawnNpc(npcCfgId, mapId, x, y, 0, expireTs)
    if npc then
        return "刷NPC成功 instId="..npc.inst_id
    else
        return "NPC配置不存在"
    end
end, "npc_spawn npc_cfg_id [mapId] [x] [y] [liveSec] 刷NPC")

-- 删除NPC
GMMgr:RegisterCmd("npc_del", 2, function(player, args)
    local instId = tonumber(args[1])
    local ok = NpcMgr:DespawnNpc(instId)
    return ok and "删除成功" or "NPC不存在"
end, "npc_del inst_id 删除NPC实例")

-- 重载NPC静态配置(热更)
GMMgr:RegisterCmd("npc_reload", 1, function()
    NpcMgr:Init()
    return "静态NPC重载完成"
end, "npc_reload 重载全部静态NPC")

9. 业务坑点

  1. 距离校验:必须校验交互距离,防止远程点NPC商店/传送
  2. 实例ID隔离:cfg_id是模板,inst_id是地图上的实体,一张图可以多个同模板NPC
  3. 动态NPC:活动NPC用expire_ts,过期自动清,重启服务器会丢失;持久活动NPC要落地库
  4. 脚本解耦:NpcMgr只做调度,商店交给ShopMgr、任务交给QuestMgr,职责拆分
  5. 地图广播:刷/删NPC实时推送给当前地图玩家,进入地图一次性全量下发
相关推荐
花椒技术2 天前
从“实时生成游戏”出发,我们用 AI 做了四次游戏开发尝试
人工智能·aigc·游戏开发
浪浪山_大橙子2 天前
我用 GPT‑6.2 打磨《大国崛起》4.0.1,从雪地脚印改到运输跑道
游戏开发
翼帆2 天前
我用 AI 复刻了 CodeTank,重温代码坦克
前端·javascript·开源·ai编程·游戏开发·codetank
花椒技术3 天前
客户端团队用 AI 做直播间桌球,状态同步和渲染怎么落地
agent·ai编程·游戏开发
羲云网络4 天前
Claude Fable 5.2 创意编程分析:程序化生成、多智能体协作与工程验收
人工智能·大语言模型·blender·游戏开发
SmalBox5 天前
10-04-实战-资源组织与依赖管理实战
unity3d·游戏开发
浪浪山_大橙子7 天前
被1.4 MB的射击游戏震撼后,我认真拆了一遍Fable的实现
ai编程·游戏开发·three.js
SmalBox7 天前
10-02-实战-Unity原生AssetBundle实战
unity3d·游戏开发
SmalBox8 天前
10-01-实战-环境搭建与集成
unity3d·游戏开发