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

мНет описания правки
мНет описания правки
(не показано 50 промежуточных версий этого же участника)
Строка 2: Строка 2:
local jobData          = mw.loadData("Модуль:IanComradeBot/job.json/data")
local jobData          = mw.loadData("Модуль:IanComradeBot/job.json/data")
local gearData          = mw.loadData("Модуль:IanComradeBot/startingGear.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 gearloadout      = mw.loadData("Модуль:IanComradeBot/loadout.json/data")
local gearloadoutGroup  = mw.loadData("Модуль:IanComradeBot/loadoutGroup.json/data")
local gearloadoutGroup  = mw.loadData("Модуль:IanComradeBot/loadoutGroup.json/data")
Строка 7: Строка 8:
local p = {}
local p = {}


function p.main(frame)
-- Функция для создания кэша по id
     local args = frame.args
local function createCache(tbl)
    local slot  = args[1] or ""
     local cache = {}
    local jobId = args[2] or ""
    for k, v in pairs(tbl) do
   
        if v.id then
    if slot == "" or jobId == "" then
            cache[v.id] = v
         return "Ошибка: Не заданы необходимые параметры. Используйте: {{#invoke:Prototypes/Роль/Экипировка|main|<slot>|<jobId>}}"
        else
            cache[k] = v
         end
     end
     end
    return cache
end


    -- Поиск должности по id
-- Кэши для данных
     local job = nil
local jobCache          = createCache(jobData)
     for k, v in pairs(jobData) do
local gearCache          = createCache(gearData)
         local curId = v.id or k
local roleLoadoutCache  = createCache(gearRoleLoadout)
         if string.lower(curId) == string.lower(jobId) then
local loadoutCache      = createCache(gearloadout)
            job = v
local loadoutGroupCache  = createCache(gearloadoutGroup)
            break
 
-- Функция для поиска объекта по 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
         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
     if not job then
end
         return "Ошибка: не найдена должность с id " .. jobId
 
-- Функция для обработки результата в зависимости от режима 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
end


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


     -- Поиск набора экипировки в gearData по id
     -- Режим "special": обработка имплантов через данные должности
     local gear = nil
     if param == "special" then
    for k, v in pairs(gearData) do
        local job = findById(jobCache, capitalizeFirst(idParam))
         local curId = v.id or k
        if not job then
         if string.lower(curId) == string.lower(gearId) then
            return ""
             gear = v
        end
             break
         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
     end
     end
     if not gear then
 
        return "Ошибка: не найдена экипировка с id " .. gearId
     -- Определяем режим "radio" (например, param == "radio" заменяет слот на "ears")
     end
     local radioMode = false
     if not gear.equipment then
    local slot = param
         return "Ошибка: в экипировке с id " .. gearId .. " отсутствует раздел equipment"
     if param == "radio" then
         radioMode = true
        slot = "ears"
     end
     end


     -- 1. Попытка получить экипировку из gearData
    local itemId = ""
     local itemId = gear.equipment[slot]
    local sourceGear = nil
     local sourceGear = gear  -- объект, откуда взята экипировка (например, для слота "back")
 
     -- Пробуем найти запись роли в gearRoleLoadout по ключу "Job" + idParam (с заглавной буквы)
     local roleLoadoutId = "Job" .. capitalizeFirst(idParam)
     local roleLoadoutData = findById(roleLoadoutCache, roleLoadoutId)
      
      
     -- Если значение не найдено – переходим к поиску через loadoutGroup
     if not roleLoadoutData then
    if itemId == nil or itemId == "" then
        -- Если запись роли НЕ найдена, то воспринимаем второй параметр как идентификатор набора экипировки (startingGear)
         local combinedId = jobId .. slot
        local gear = findById(gearCache, idParam)
         local groupEntry = nil
        if not gear then
         for key, v in pairs(gearloadoutGroup) do
            return "Ошибка: не найдена экипировка с id " .. idParam
             local curId = v.id or key
        end
             if string.lower(curId) == string.lower(combinedId) then
        local gearEquipment = gear.equipment or {}
                groupEntry = v
        itemId = gearEquipment[slot] or ""
                break
        if itemId == "" then
             end
            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
         end
         if groupEntry and groupEntry.loadouts and #groupEntry.loadouts > 0 then
 
            -- Берём первый id из loadouts
         local gearEquipment = gear.equipment or {}
            local firstLoadoutId = groupEntry.loadouts[1]
        itemId = gearEquipment[slot] or ""
            local loadoutEntry = nil
        sourceGear = gear
             for key, v in pairs(gearloadout) do
       
                 local curId = v.id or key
        -- Если для данного слота ничего не найдено в базовом наборе, пытаемся найти его через roleLoadout
                if string.lower(curId) == string.lower(firstLoadoutId) then
        if itemId == "" then
                    loadoutEntry = v
             for _, groupId in ipairs(roleLoadoutData.groups or {}) do
                     break
                 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
            end
                if itemId ~= "" then break end
            if loadoutEntry and loadoutEntry.equipment then
                itemId = loadoutEntry.equipment[slot]
                sourceGear = loadoutEntry
             end
             end
         end
         end
     end
     end
 
   
     -- Если экипировка так и не найдена, возвращаем пустую строку
     -- Если экипировка так и не найдена, возвращаем пустую строку
     if itemId == nil or itemId == "" then
     if itemId == "" then
         return ""
         return ""
     end
     end


     -- Вывод результата
     local result = buildResult(itemId, sourceGear, slot)
    if slot == "back" and sourceGear.storage and sourceGear.storage.back then
    return processResult(itemId, result, radioMode, frame)
        local storageBack = ""
        for _, storageItem in ipairs(sourceGear.storage.back) do
            storageBack = storageBack .. string.format("{{#invoke:Prototypes/Предмет/Содержание|main|%s}}", storageItem)
        end
        return frame:preprocess(string.format("{{#invoke:Prototypes/Предмет/Содержание|image|%s|%s}}", itemId, storageBack))
    else
        return frame:preprocess(string.format("{{#invoke:Prototypes/Предмет/Содержание|image|%s}}", itemId))
    end
end
end


return p
return p