Модуль:Песочница/Pok: различия между версиями

Нет описания правки
Нет описания правки
Метка: ручная отмена
Строка 1: Строка 1:
-- Загрузка данных
local data = mw.loadData("Модуль:IanComradeBot/prototypes/fills/Item.json/data")
local allSelectorData = mw.loadData("Модуль:IanComradeBot/prototypes/table.json/data")
local p = {}
local p = {}


-- Загружаем данные из отдельных модулей
-- Функция для загрузки данных
local itemData = mw.loadData("Модуль:IanComradeBot/prototypes/fills/Item.json/data")
local loadData = function(filePath)
local tableData = mw.loadData("Модуль:IanComradeBot/prototypes/table.json/data")
    local page = mw.title.new(filePath)
    local content = page:getContent()
    return content and mw.text.jsonDecode(content) or nil
end


-- Локализация всех функций
-- Функция processRolls для преобразования диапазона
local processRolls, buildIndex, findDataById, formatContent, getContentsOutput,
local processRolls = function(rolls)
      processNestedSelectors, getTableOutput, getContainedOutput, handleAllSelector,
      handleGroupSelector, handleNestedSelector, getChemOutput
 
-----------------------------------------------------------
processRolls = function(rolls)
     local result = {}
     local result = {}
     if rolls and rolls.range then
     if rolls and rolls.range then
        -- Если указан range
         local min, max = rolls.range:match("(%d+),%s*(%d+)")
         local min, max = rolls.range:match("(%d+),%s*(%d+)")
         min, max = tonumber(min), tonumber(max)
         min, max = tonumber(min), tonumber(max)
Строка 22: Строка 25:
         end
         end
     elseif rolls and rolls.value then
     elseif rolls and rolls.value then
        -- Если указано value
         result[#result + 1] = string.format('[%d]', rolls.value)
         result[#result + 1] = string.format('[%d]', rolls.value)
     else
     else
Строка 29: Строка 33:
end
end


-----------------------------------------------------------
-- Локальные функции
buildIndex = function(data)
local findDataById, formatContent, getContentsOutput, processNestedSelectors, getTableOutput, getContainedOutput, getChemOutput, handleGroupSelector, handleAllSelector, handleNestedSelector
 
-- Функция для создания хэш-таблицы для быстрого поиска по ID
local function buildIndex(data)
     if not data then return {} end
     if not data then return {} end
     local index = {}
     local index = {}
Строка 39: Строка 46:
end
end


-----------------------------------------------------------
-- Поиск данных по ID через индекс
findDataById = function(dataIndex, id)
findDataById = function(dataIndex, id)
     return dataIndex and dataIndex[id] or nil
     return dataIndex and dataIndex[id] or nil
end
end


-----------------------------------------------------------
-- Форматирование содержимого
formatContent = function(content)
formatContent = function(content)
     if not content.id then
     if not content.id then
Строка 52: Строка 59:
     local name = string.format('{{#invoke:Entity Lookup|getname|%s}}', content.id)
     local name = string.format('{{#invoke:Entity Lookup|getname|%s}}', content.id)
     local image = string.format('%s.png', content.id)
     local image = string.format('%s.png', content.id)
    local amount = (content.amount and content.amount ~= 1) and string.format(" [%d]", content.amount) or ""
local amount = (content.amount and content.amount ~= 1) and string.format(" [%d]", content.amount) or ""
     local prob = ""
     local prob = ""


Строка 60: Строка 67:


     if content.prob then
     if content.prob then
         prob = string.format(" <div>%s%%</div>",  
         prob = string.format(" <div>%s%%</div>", content.prob * 100 >= 1 and math.floor(content.prob * 100) or content.prob * 100)
            content.prob * 100 >= 1 and math.floor(content.prob * 100) or content.prob * 100)
     end
     end


     return string.format(
     return string.format(
         '{{LinkСard|SideStyle=1|background-color=#cbcbff0b|image=%s|name=%s%s%s {{#invoke:Prototypes/Хранилище/Предмет|main|framing|contained|%s}} }}',
         '{{LinkСard|SideStyle=1|background-color=#cbcbff0a|image=%s|name=%s%s%s {{#invoke:Prototypes/Хранилище/Предмет|main|framing|contained|%s}} }}',
         image, name, amount, prob, content.id
         image, name, amount, prob, content.id
     )
     )
end
end


-----------------------------------------------------------
-- Получение содержимого через таблицу
getContentsOutput = function(contents)
getContentsOutput = function(contents)
     local result = {}
     local result = {}
Строка 79: Строка 85:
end
end


-----------------------------------------------------------
-- Обработка вложенных таблиц
processNestedSelectors = function(children)
processNestedSelectors = function(children)
     if not children or #children == 0 then return "" end
     if not children or #children == 0 then return "" end


     local results = {}
     local results = {}
     for _, child in ipairs(children) do
     for _, child in ipairs(children) do
         if child.id then
         if child.id then
Строка 97: Строка 104:
end
end


-----------------------------------------------------------
-- Обработка таблиц
getTableOutput = function(tableId)
getTableOutput = function(tableId)
     local tableIndex = buildIndex(tableData)
     local allSelectors = loadData('User:IanComradeBot/prototypes/table.json')
     local tableItem = findDataById(tableIndex, tableId)
     local tableData = findDataById(buildIndex(allSelectors), tableId)
     if not tableItem then return 'Таблица не найдена.' end
 
     if not tableData then return 'Таблица не найдена.' end


     if tableItem['!type:GroupSelector'] then
     if tableData['!type:GroupSelector'] then
         return handleGroupSelector(tableItem['!type:GroupSelector'])
         return handleGroupSelector(tableData['!type:GroupSelector'])
     elseif tableItem['!type:AllSelector'] then
     elseif tableData['!type:AllSelector'] then
         return processNestedSelectors(tableItem['!type:AllSelector'].children)
         return processNestedSelectors(tableData['!type:AllSelector'].children)
     end
     end


Строка 112: Строка 120:
end
end


-----------------------------------------------------------
-- Формирование списка содержащихся предметов или таблиц
getContainedOutput = function(dataIndex, id)
getContainedOutput = function(data, id)
     local item = findDataById(dataIndex, id)
     local item = findDataById(data, id)
     if not item then return '' end
     if not item then return '' end


     local result = {}
     local result = {}


    -- Обработка StorageFill
     if item.StorageFill and item.StorageFill.contents then
     if item.StorageFill and item.StorageFill.contents then
         result[#result + 1] = getContentsOutput(item.StorageFill.contents)
         result[#result + 1] = getContentsOutput(item.StorageFill.contents)
    -- Обработка EntityTableContainerFill
     elseif item.EntityTableContainerFill and item.EntityTableContainerFill.containers then
     elseif item.EntityTableContainerFill and item.EntityTableContainerFill.containers then
         local containers = item.EntityTableContainerFill.containers
         local containers = item.EntityTableContainerFill.containers


        -- Обработка entity_storage
         if containers.entity_storage then
         if containers.entity_storage then
             if containers.entity_storage.children then
             if containers.entity_storage.children then
                 result[#result + 1] = processNestedSelectors(containers.entity_storage.children)
                 result[#result + 1] = processNestedSelectors(containers.entity_storage.children)
             end
             end
             if containers.entity_storage.tableId then
             if containers.entity_storage.tableId then
                 result[#result + 1] = getTableOutput(containers.entity_storage.tableId)
                 result[#result + 1] = getTableOutput(containers.entity_storage.tableId)
Строка 133: Строка 146:
         end
         end


        -- Обработка storagebase
         if containers.storagebase and containers.storagebase.tableId then
         if containers.storagebase and containers.storagebase.tableId then
             result[#result + 1] = getTableOutput(containers.storagebase.tableId)
             result[#result + 1] = getTableOutput(containers.storagebase.tableId)
Строка 141: Строка 155:
end
end


-----------------------------------------------------------
-- Обработка AllSelector
handleAllSelector = function(allSelector)
handleAllSelector = function(allSelector)
     if not allSelector.children then return '' end
     if not allSelector.children then return '' end
Строка 147: Строка 161:
end
end


-----------------------------------------------------------
-- Обработка GroupSelector
handleGroupSelector = function(groupSelector)
handleGroupSelector = function(groupSelector)
     if not groupSelector.children then return '' end
     if not groupSelector.children then return '' end
Строка 153: Строка 167:
     local wrapperStart, wrapperEnd = "", ""
     local wrapperStart, wrapperEnd = "", ""


    -- Проверка для контейнера EntityTableContainerFill
     if groupSelector.weight and groupSelector.weight ~= "default" then
     if groupSelector.weight and groupSelector.weight ~= "default" then
         wrapperStart = string.format('{{LinkСard/Сollapsible|name=Группа предметов %s%%|content=', groupSelector.weight)
         wrapperStart = string.format('{{LinkСard/Сollapsible|name=Группа предметов %s%%|content=', groupSelector.weight)
Строка 176: Строка 191:
end
end


-----------------------------------------------------------
-- Обработка NestedSelector
handleNestedSelector = function(nestedSelector, wrapped)
handleNestedSelector = function(nestedSelector, wrapped)
     if not nestedSelector.tableId then return '' end
     if not nestedSelector.tableId then return '' end


     local result = {}
     local result = {}
     local classesRolls, classesProb
     local classesRolls, classesProb


     if wrapped then
     if wrapped then
        if nestedSelector.rolls and nestedSelector.rolls.range then
if nestedSelector.rolls and nestedSelector.rolls.range then
            local rollsResult = processRolls(nestedSelector.rolls)
    local rollsResult = processRolls(nestedSelector.rolls)
            if rollsResult and #rollsResult > 0 then
    if rollsResult and #rollsResult > 0 then
                classesRolls = ', максимум может выпасть: ' .. rollsResult
        classesRolls = ', максимум может выпасть: ' .. rollsResult
            end
    end
        end
end
         if nestedSelector.prob then
         if nestedSelector.prob then
             classesProb = string.format(" <div>%s%%</div>",  
             classesProb = string.format(" <div>%s%%</div>", nestedSelector.prob * 100 >= 1 and math.floor(nestedSelector.prob * 100) or nestedSelector.prob * 100)
                nestedSelector.prob * 100 >= 1 and math.floor(nestedSelector.prob * 100) or nestedSelector.prob * 100)
         end
         end
     end
     end


    if wrapped and (classesRolls or classesProb) then
if wrapped and (classesRolls or classesProb) then
        result[#result + 1] = string.format('{{LinkСard/Сollapsible|name=Группа предметов%s%s|content=', classesRolls or "", classesProb or "")
    if (classesRolls and #classesRolls > 0) or (classesProb and #classesProb > 0) then
    end
        result[#result + 1] = string.format('{{LinkСard/Сollapsible|name=Группа предметов%s%s|content=', classesRolls or "", classesProb or "")
    end
end


     result[#result + 1] = getTableOutput(nestedSelector.tableId)
     result[#result + 1] = getTableOutput(nestedSelector.tableId)


    if wrapped and (classesRolls or classesProb) then
if wrapped and (classesRolls or classesProb) then
    if (classesRolls and #classesRolls > 0) or (classesProb and #classesProb > 0) then
         result[#result + 1] = "}}"
         result[#result + 1] = "}}"
    end
    end
end


     return table.concat(result)
     return table.concat(result)
end
end


-----------------------------------------------------------
-- Формирование списка химии
getChemOutput = function(dataIndex, id)
getChemOutput = function(data, id)
     local item = findDataById(dataIndex, id)
     local item = findDataById(data, id)
     if not item or not item.SolutionContainerManager or not item.SolutionContainerManager.solutions then  
     if not item or not item.SolutionContainerManager or not item.SolutionContainerManager.solutions then return '' end
        return ''  
    end


     local result = {}
     local result = {}
     for _, solution in pairs(item.SolutionContainerManager.solutions) do
     for _, solution in pairs(item.SolutionContainerManager.solutions) do
         for _, reagent in ipairs(solution.reagents) do
         for _, reagent in ipairs(solution.reagents) do
             result[#result + 1] = string.format(
             result[#result + 1] = string.format('<li>[[Химия#chem_%s|%s]] (%d ед.)</li>', reagent.ReagentId, reagent.ReagentId, reagent.Quantity)
                '<li>[[Химия#chem_%s|%s]] (%d ед.)</li>',  
                reagent.ReagentId, reagent.ReagentId, reagent.Quantity)
         end
         end
     end
     end
Строка 227: Строка 242:
end
end


-----------------------------------------------------------
-- Основная функция модуля
function p.main(frame)
function p.main(frame)
     local mode = frame.args[1]
     local mode = frame.args[1]
     local id = frame.args[2]
     local id = frame.args[2]


     if not id then  
     if not id then return 'Не указан ID.' end
        return 'Не указан ID.'  
      
     end
local dataIndex = buildIndex(data)
 
    local itemIndex = buildIndex(itemData)
     if not data then return 'Не удалось загрузить данные.' end
     if not itemData then  
        return 'Не удалось загрузить данные.'  
    end


     if mode == 'framing' then
     if mode == 'framing' then
         local subMode = frame.args[2]
         local subMode = frame.args[2]
         local id = frame.args[3]
         local id = frame.args[3]
         if not id then
         if not id then
             return 'Не указан ID для режима framing.'
             return 'Не указан ID для режима framing.'
Строка 249: Строка 262:


         if subMode == 'chem' then
         if subMode == 'chem' then
             return frame:preprocess('{{СollapsibleMenu|' .. getChemOutput(itemIndex, id) .. '}}')
             return frame:preprocess('{{СollapsibleMenu|' .. getChemOutput(dataIndex, id) .. '}}')
         elseif subMode == 'contained' then
         elseif subMode == 'contained' then
             return frame:preprocess('{{СollapsibleMenu|' .. getContainedOutput(itemIndex, id) .. '}}')
             return frame:preprocess('{{СollapsibleMenu|' .. getContainedOutput(dataIndex, id) .. '}}')
         else
         else
             return 'Неизвестный подрежим для framing: ' .. subMode
             return 'Неизвестный подрежим для framing: ' .. subMode
         end
         end
     elseif mode == 'chem' then
     elseif mode == 'chem' then
         return frame:preprocess(getChemOutput(itemIndex, id))
         return frame:preprocess(getChemOutput(dataIndex, id))
     elseif mode == 'contained' then
     elseif mode == 'contained' then
         return frame:preprocess(getContainedOutput(itemIndex, id))
         return frame:preprocess(getContainedOutput(dataIndex, id))
     elseif mode == 'rolls' then
     elseif mode == 'rolls' then
         local entity = findDataById(itemIndex, id)
         local entity = findDataById(dataIndex, id)
         if not entity then  
         if not entity then return 'ID не найден в данных.' end
            return 'ID не найден в данных.'  
        end


         if entity.EntityTableContainerFill then
         if entity.EntityTableContainerFill then