Модуль:Prototypes/Роль/Экипировка: различия между версиями

Материал из Space Station 14 Вики
мНет описания правки
мНет описания правки
 
(не показано 38 промежуточных версий этого же участника)
Строка 1: Строка 1:
-- Загрузка данных
local jobData          = mw.loadData("Модуль:IanComradeBot/job.json/data")
local gearData          = mw.loadData("Модуль:IanComradeBot/startingGear.json/data")
local gearRoleLoadout  = mw.loadData("Модуль:IanComradeBot/roleLoadout.json/data")
local gearloadout      = mw.loadData("Модуль:IanComradeBot/loadout.json/data")
local gearloadoutGroup  = mw.loadData("Модуль:IanComradeBot/loadoutGroup.json/data")
local p = {}
local p = {}


function p.main(frame)
-- Функция для создания кэша по id
     local args = frame.args
local function createCache(tbl)
     local slot = args[1]
     local cache = {}
     local role = args[2]
    for k, v in pairs(tbl) do
        if v.id then
            cache[v.id] = v
        else
            cache[k] = v
        end
     end
    return cache
end
 
-- Кэши для данных
local jobCache          = createCache(jobData)
local gearCache          = createCache(gearData)
local roleLoadoutCache  = createCache(gearRoleLoadout)
local loadoutCache      = createCache(gearloadout)
local loadoutGroupCache  = createCache(gearloadoutGroup)
 
-- Функция для поиска объекта по id
local function findById(tbl, id)
    return tbl[id]
end
 
-- Функция для преобразования первой буквы строки в заглавную
local function capitalizeFirst(str)
     if not str or str == "" then return "" end
    return str:sub(1,1):upper() .. str:sub(2)
end


     if not slot or not role then
-- Функция для сборки результата экипировки
         return "Ошибка: не указан слот или роль."
local function buildResult(itemId, sourceGear, slot)
     if slot == "back" and sourceGear.storage and sourceGear.storage.back then
        local storageBack = ""
        for _, storageItem in ipairs(sourceGear.storage.back) do
            storageBack = storageBack .. string.format("{{Предмет|%s}}", storageItem)
        end
         return string.format("<div>{{Предмет|%s|repository=|size=64px|label=|imageTooltip=}} {{СollapsibleMenu|%s}}</div>", itemId, storageBack)
    else
        return string.format("{{Предмет|%s|repository=|size=64px|label=|imageTooltip=}}", itemId)
     end
     end
end


     local gearloadout = mw.loadData("Модуль:IanComradeBot/loadout.json/data")
-- Функция для обработки результата в зависимости от режима radio
     local gearloadoutGroup = mw.loadData("Модуль:IanComradeBot/loadoutGroup.json/data")
local function processResult(itemId, result, radioMode, frame)
     if radioMode then
        return frame:preprocess(string.format("{{#invoke:Prototypes/Механика/Частоты|main|%s}}", itemId))
     else
        return frame:preprocess(result)
    end
end


     local function capitalize(s)
function p.main(frame)
         return (s:gsub("^%l", string.upper))
     local args = frame.args
    local param  = mw.text.trim(args[1] or "")
    local idParam = mw.text.trim(args[2] or "")
   
    if param == "" or idParam == "" then
         return "Ошибка: Не заданы необходимые параметры. Используйте: {{#invoke:Prototypes/Роль/Экипировка|main|<slot/special/radio>|<jobId или startingGearId>}}"
     end
     end


     local groupID = role .. capitalize(slot)
     -- Режим "special": обработка имплантов через данные должности
    if param == "special" then
        local job = findById(jobCache, capitalizeFirst(idParam))
        if not job then
            return ""
        end
        local specials = job.special or {}
        local implantsList = {}
        for _, special in ipairs(specials) do
            if special["!type"] == "AddImplantSpecial" and special.implants then
                for _, implant in ipairs(special.implants) do
                    table.insert(implantsList, string.format("{{#invoke:Entity Lookup|getname|%s}}", implant))
                end
            end
        end


    local groupFound = nil
        if #implantsList > 0 then
    for _, group in ipairs(gearloadoutGroup) do
            return frame:preprocess(table.concat(implantsList, ", "))
         if group.id == groupID then
         else
            groupFound = group
             return ""
             break
         end
         end
     end
     end


     if not groupFound then
    -- Определяем режим "radio" (например, param == "radio" заменяет слот на "ears")
         return "Группа не найдена: " .. groupID
    local radioMode = false
    local slot = param
     if param == "radio" then
         radioMode = true
        slot = "ears"
     end
     end


     for _, loadoutID in ipairs(groupFound.loadouts) do
     local itemId = ""
        for _, loadout in ipairs(gearloadout) do
    local sourceGear = nil
            if loadout.id == loadoutID then
 
                if loadout.equipment and loadout.equipment[slot] then
    -- Пробуем найти запись роли в gearRoleLoadout по ключу "Job" + idParam (с заглавной буквы)
                    return loadout.equipment[slot]
    local roleLoadoutId = "Job" .. capitalizeFirst(idParam)
    local roleLoadoutData = findById(roleLoadoutCache, roleLoadoutId)
   
    if not roleLoadoutData then
        -- Если запись роли НЕ найдена, то воспринимаем второй параметр как идентификатор набора экипировки (startingGear)
        local gear = findById(gearCache, idParam)
        if not gear then
            return "Ошибка: не найдена экипировка с id " .. idParam
        end
        local gearEquipment = gear.equipment or {}
        itemId = gearEquipment[slot] or ""
        if itemId == "" then
            return ""
        end
        sourceGear = gear
    else
        -- Если запись роли найдена, то обрабатываем через данные должности
        local jobId = capitalizeFirst(idParam)
        local job = findById(jobCache, jobId)
        if not job then
            return "Ошибка: не найдена должность с id " .. jobId
        end
 
        local gearId = job.startingGear
        if not gearId then
            return "Ошибка: у должности с id " .. jobId .. " не указан startingGear"
        end
 
        local gear = findById(gearCache, gearId)
        if not gear then
            return "Ошибка: не найдена экипировка с id " .. gearId
        end
 
        local gearEquipment = gear.equipment or {}
        itemId = gearEquipment[slot] or ""
        sourceGear = gear
       
        -- Если для данного слота ничего не найдено в базовом наборе, пытаемся найти его через roleLoadout
        if itemId == "" then
            for _, groupId in ipairs(roleLoadoutData.groups or {}) do
                if groupId ~= "Trinkets" then  -- исключаем группу Trinkets
                    local groupFound = findById(loadoutGroupCache, groupId)
                    if groupFound and type(groupFound.loadouts) == "table" then
                        for _, loadoutID in ipairs(groupFound.loadouts) do
                            local loadout = findById(loadoutCache, loadoutID)
                            if loadout and not loadout.effects and loadout.equipment and loadout.equipment[slot] then
                                itemId = loadout.equipment[slot]
                                sourceGear = loadout
                                break
                            end
                        end
                    end
                 end
                 end
                if itemId ~= "" then break end
             end
             end
         end
         end
    end
   
    -- Если экипировка так и не найдена, возвращаем пустую строку
    if itemId == "" then
        return ""
     end
     end


     return "Экипировка не найдена для слота: " .. slot
    local result = buildResult(itemId, sourceGear, slot)
     return processResult(itemId, result, radioMode, frame)
end
end


return p
return p

Текущая версия от 09:54, 4 апреля 2025

Для документации этого модуля может быть создана страница Модуль:Prototypes/Роль/Экипировка/doc

-- Загрузка данных
local jobData           = mw.loadData("Модуль:IanComradeBot/job.json/data")
local gearData          = mw.loadData("Модуль:IanComradeBot/startingGear.json/data")
local gearRoleLoadout   = mw.loadData("Модуль:IanComradeBot/roleLoadout.json/data")
local gearloadout       = mw.loadData("Модуль:IanComradeBot/loadout.json/data")
local gearloadoutGroup  = mw.loadData("Модуль:IanComradeBot/loadoutGroup.json/data")

local p = {}

-- Функция для создания кэша по id
local function createCache(tbl)
    local cache = {}
    for k, v in pairs(tbl) do
        if v.id then
            cache[v.id] = v
        else
            cache[k] = v
        end
    end
    return cache
end

-- Кэши для данных
local jobCache           = createCache(jobData)
local gearCache          = createCache(gearData)
local roleLoadoutCache   = createCache(gearRoleLoadout)
local loadoutCache       = createCache(gearloadout)
local loadoutGroupCache  = createCache(gearloadoutGroup)

-- Функция для поиска объекта по id
local function findById(tbl, id)
    return tbl[id]
end

-- Функция для преобразования первой буквы строки в заглавную
local function capitalizeFirst(str)
    if not str or str == "" then return "" end
    return str:sub(1,1):upper() .. str:sub(2)
end

-- Функция для сборки результата экипировки
local function buildResult(itemId, sourceGear, slot)
    if slot == "back" and sourceGear.storage and sourceGear.storage.back then
        local storageBack = ""
        for _, storageItem in ipairs(sourceGear.storage.back) do
            storageBack = storageBack .. string.format("{{Предмет|%s}}", storageItem)
        end
        return string.format("<div>{{Предмет|%s|repository=|size=64px|label=|imageTooltip=}} {{СollapsibleMenu|%s}}</div>", itemId, storageBack)
    else
        return string.format("{{Предмет|%s|repository=|size=64px|label=|imageTooltip=}}", itemId)
    end
end

-- Функция для обработки результата в зависимости от режима radio
local function processResult(itemId, result, radioMode, frame)
    if radioMode then
        return frame:preprocess(string.format("{{#invoke:Prototypes/Механика/Частоты|main|%s}}", itemId))
    else
        return frame:preprocess(result)
    end
end

function p.main(frame)
    local args = frame.args
    local param   = mw.text.trim(args[1] or "")
    local idParam = mw.text.trim(args[2] or "")
    
    if param == "" or idParam == "" then
        return "Ошибка: Не заданы необходимые параметры. Используйте: {{#invoke:Prototypes/Роль/Экипировка|main|<slot/special/radio>|<jobId или startingGearId>}}"
    end

    -- Режим "special": обработка имплантов через данные должности
    if param == "special" then
        local job = findById(jobCache, capitalizeFirst(idParam))
        if not job then
            return ""
        end
        local specials = job.special or {}
        local implantsList = {}
        for _, special in ipairs(specials) do
            if special["!type"] == "AddImplantSpecial" and special.implants then
                for _, implant in ipairs(special.implants) do
                    table.insert(implantsList, string.format("{{#invoke:Entity Lookup|getname|%s}}", implant))
                end
            end
        end

        if #implantsList > 0 then
            return frame:preprocess(table.concat(implantsList, ", "))
        else
            return ""
        end
    end

    -- Определяем режим "radio" (например, param == "radio" заменяет слот на "ears")
    local radioMode = false
    local slot = param
    if param == "radio" then
        radioMode = true
        slot = "ears"
    end

    local itemId = ""
    local sourceGear = nil

    -- Пробуем найти запись роли в gearRoleLoadout по ключу "Job" + idParam (с заглавной буквы)
    local roleLoadoutId = "Job" .. capitalizeFirst(idParam)
    local roleLoadoutData = findById(roleLoadoutCache, roleLoadoutId)
    
    if not roleLoadoutData then
        -- Если запись роли НЕ найдена, то воспринимаем второй параметр как идентификатор набора экипировки (startingGear)
        local gear = findById(gearCache, idParam)
        if not gear then
            return "Ошибка: не найдена экипировка с id " .. idParam
        end
        local gearEquipment = gear.equipment or {}
        itemId = gearEquipment[slot] or ""
        if itemId == "" then
            return ""
        end
        sourceGear = gear
    else
        -- Если запись роли найдена, то обрабатываем через данные должности
        local jobId = capitalizeFirst(idParam)
        local job = findById(jobCache, jobId)
        if not job then
            return "Ошибка: не найдена должность с id " .. jobId
        end

        local gearId = job.startingGear
        if not gearId then
            return "Ошибка: у должности с id " .. jobId .. " не указан startingGear"
        end

        local gear = findById(gearCache, gearId)
        if not gear then
            return "Ошибка: не найдена экипировка с id " .. gearId
        end

        local gearEquipment = gear.equipment or {}
        itemId = gearEquipment[slot] or ""
        sourceGear = gear
        
        -- Если для данного слота ничего не найдено в базовом наборе, пытаемся найти его через roleLoadout
        if itemId == "" then
            for _, groupId in ipairs(roleLoadoutData.groups or {}) do
                if groupId ~= "Trinkets" then  -- исключаем группу Trinkets
                    local groupFound = findById(loadoutGroupCache, groupId)
                    if groupFound and type(groupFound.loadouts) == "table" then
                        for _, loadoutID in ipairs(groupFound.loadouts) do
                            local loadout = findById(loadoutCache, loadoutID)
                            if loadout and not loadout.effects and loadout.equipment and loadout.equipment[slot] then
                                itemId = loadout.equipment[slot]
                                sourceGear = loadout
                                break
                            end
                        end
                    end
                end
                if itemId ~= "" then break end
            end
        end
    end
    
    -- Если экипировка так и не найдена, возвращаем пустую строку
    if itemId == "" then
        return ""
    end

    local result = buildResult(itemId, sourceGear, slot)
    return processResult(itemId, result, radioMode, frame)
end

return p