Модуль:Prototypes/Роль/Экипировка: различия между версиями
Материал из Space Station 14 Вики
Pok (обсуждение | вклад) мНет описания правки |
Pok (обсуждение | вклад) мНет описания правки |
||
(не показано 36 промежуточных версий этого же участника) | |||
Строка 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 = {} | ||
-- Функция для | -- Функция для создания кэша по id | ||
local function | local function createCache(tbl) | ||
local cache = {} | |||
for k, v in pairs(tbl) do | for k, v in pairs(tbl) do | ||
if | if v.id then | ||
cache[v.id] = v | |||
else | |||
cache[k] = v | |||
end | end | ||
end | end | ||
return | 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 | end | ||
Строка 21: | Строка 37: | ||
if not str or str == "" then return "" end | if not str or str == "" then return "" end | ||
return str:sub(1,1):upper() .. str:sub(2) | 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 | end | ||
function p.main(frame) | function p.main(frame) | ||
local args = frame.args | local args = frame.args | ||
local | local param = mw.text.trim(args[1] or "") | ||
local | local idParam = mw.text.trim(args[2] or "") | ||
if | if param == "" or idParam == "" then | ||
return "Ошибка: Не заданы необходимые параметры. Используйте: {{#invoke:Prototypes/Роль/Экипировка|main|<slot>|<jobId>}}" | return "Ошибка: Не заданы необходимые параметры. Используйте: {{#invoke:Prototypes/Роль/Экипировка|main|<slot/special/radio>|<jobId или startingGearId>}}" | ||
end | 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 | end | ||
-- | -- Определяем режим "radio" (например, param == "radio" заменяет слот на "ears") | ||
local | local radioMode = false | ||
if | local slot = param | ||
if param == "radio" then | |||
radioMode = true | |||
slot = "ears" | |||
end | end | ||
local | local itemId = "" | ||
local sourceGear = nil | |||
-- | -- Пробуем найти запись роли в gearRoleLoadout по ключу "Job" + idParam (с заглавной буквы) | ||
local | local roleLoadoutId = "Job" .. capitalizeFirst(idParam) | ||
local | local roleLoadoutData = findById(roleLoadoutCache, roleLoadoutId) | ||
-- | if not roleLoadoutData then | ||
-- Если запись роли НЕ найдена, то воспринимаем второй параметр как идентификатор набора экипировки (startingGear) | |||
-- | local gear = findById(gearCache, idParam) | ||
local | if not gear then | ||
return | 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 | end | ||
local gearId = job.startingGear | |||
local | if not gearId then | ||
return "Ошибка: у должности с id " .. jobId .. " не указан startingGear" | |||
end | end | ||
if not | local gear = findById(gearCache, gearId) | ||
return " | if not gear then | ||
return "Ошибка: не найдена экипировка с id " .. gearId | |||
end | end | ||
-- | local gearEquipment = gear.equipment or {} | ||
for _, | 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 | end | ||
if itemId ~= "" then break end | |||
end | end | ||
end | end | ||
end | end | ||
-- | -- Если экипировка так и не найдена, возвращаем пустую строку | ||
if itemId == "" then | if itemId == "" then | ||
return "" | return "" | ||
end | end | ||
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