From 926a5f3e1605f73b0560c994a0116cec5685be7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Lu=C3=ADs=20Lucarelo=20Lamonato?= Date: Tue, 2 Jul 2024 16:13:00 -0300 Subject: [PATCH] feat: possibility to persist NPC on map with /n talkaction (#2682) --- data/scripts/talkactions/god/create_npc.lua | 38 ++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/data/scripts/talkactions/god/create_npc.lua b/data/scripts/talkactions/god/create_npc.lua index 4aeec3dde80..b6d0412d391 100644 --- a/data/scripts/talkactions/god/create_npc.lua +++ b/data/scripts/talkactions/god/create_npc.lua @@ -1,3 +1,6 @@ +-- To summon a temporary npc use /n npcname +-- To summon a permanent npc use /n npcname,true + local createNpc = TalkAction("/n") function createNpc.onSay(player, words, param) @@ -9,11 +12,44 @@ function createNpc.onSay(player, words, param) return true end + local split = param:split(",") + local name = split[1] + local permanentStr = split[2] + local position = player:getPosition() - local npc = Game.createNpc(param, position) + local npc = Game.createNpc(name, position) if npc then npc:setMasterPos(position) position:sendMagicEffect(CONST_ME_MAGIC_RED) + + if permanentStr and permanentStr == "true" then + local mapName = configManager.getString(configKeys.MAP_NAME) + local mapNpcsPath = mapName .. "-npc.xml" + local filePath = string.format("%s/world/%s", DATA_DIRECTORY, mapNpcsPath) + local npcsFile = io.open(filePath, "r") + if not npcsFile then + player:sendTextMessage(MESSAGE_EVENT_ADVANCE, "There was an error when trying to add permanent NPC. NPC File not found.") + return true + end + local fileContent = npcsFile:read("*all") + npcsFile:close() + local endTag = "" + if not fileContent:find(endTag, 1, true) then + player:sendTextMessage(MESSAGE_EVENT_ADVANCE, "There was an error when trying to add permanent NPC. The NPC file format is incorrect. Missing end tag " .. endTag .. ".") + return true + end + local textToAdd = string.format('\t\n\t\t\n\t', position.x, position.y, position.z, name, position.z) + local newFileContent = fileContent:gsub(endTag, textToAdd .. "\n" .. endTag) + npcsFile = io.open(filePath, "w") + if not npcsFile then + player:sendTextMessage(MESSAGE_EVENT_ADVANCE, "There was an error when trying to write to the NPC file.") + return true + end + npcsFile:write(newFileContent) + npcsFile:close() + + player:sendTextMessage(MESSAGE_EVENT_ADVANCE, "Permanent NPC added successfully.") + end else player:sendCancelMessage("There is not enough room.") position:sendMagicEffect(CONST_ME_POFF)