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

мНет описания правки
Нет описания правки
Строка 1: Строка 1:
local p = {}
local p = {}


-- Функция для загрузки данных исследований из JSON-файла
local cachedData = nil
local function loadResearchData()
 
     return mw.text.jsonDecode(mw.title.new("User:IanComradeBot/Песочница.json"):getContent())
local function loadData(filePath)
     if cachedData then
        return cachedData
    end
    local page = mw.title.new(filePath)
    local content = page and page:getContent()
    cachedData = content and mw.text.jsonDecode(content) or nil
    return cachedData
end
end


-- Таблица для перевода названий дисциплин
local function getSpritePath(entry)
local disciplineMapping = {
     if entry.Sprite and entry.Sprite.sprite then
     Arsenal = "Арсенал",
        return entry.Sprite.sprite
     Industrial = "Промышленность",
     elseif entry.Icon and entry.Icon.sprite then
    Experimental = "Экспериментальное",
        return entry.Icon.sprite
     CivilianServices = "Обслуживание персонала"
     elseif entry.Sprite and entry.Sprite.layers then
}
        for _, layer in ipairs(entry.Sprite.layers) do
 
            if layer.sprite then
-- Таблица для цветов по уровням
                return layer.sprite
local tierColors = {
            end
    [1] = "#54d554",
        end
     [2] = "#ed9000",
     end
     [3] = "#d72a2a"
     return nil
}
end


function p.main(frame)
function p.main(frame)
     local dataCache = loadResearchData()
     local param = frame.args[1]
 
     local secondaryParam = frame.args[2]
    -- Получаем ID и иконку из параметров
    local researchId = frame.args[1] or ""
     local icon = frame.args[2] or ""


     if researchId and researchId ~= "" then
    local data = loadData('User:IanComradeBot/prototypes/entity sprite.json')
         local out = ""
     if not data or type(data) ~= 'table' then
         return 'Ошибка: Невозможно загрузить данные из JSON.'
    end


        -- Поиск исследования по ID
    if param == "image" and secondaryParam then
        local tech = nil
         for _, entry in ipairs(data) do
         for _, research in ipairs(dataCache) do
             if entry.id == secondaryParam then
             if research.technology and research.technology.id == researchId then
                 return getSpritePath(entry) or "Ошибка: Спрайт не найден."
                 tech = research.technology
                break
             end
             end
         end
         end
 
         return "Ошибка: ID не найден."
         if not tech then
            out = out .. '<div style="color:red;">Исследование с ID "' .. researchId .. '" не найдено.</div>'
        else
            local tierColor = tierColors[tech.tier] or "#FFFFFF"
            local disciplineName = disciplineMapping[tech.discipline] or "Неизвестная дисциплина"
            local iconPath = icon ~= "" and icon or (tech.icon and tech.icon.sprite or nil)
 
            -- Формирование строки необходимых исследований
            local prerequisites = ""
            if tech.technologyPrerequisites and #tech.technologyPrerequisites > 0 then
                prerequisites = '<ul>'
                for _, prerequisiteId in ipairs(tech.technologyPrerequisites) do
                    if prerequisiteId and prerequisiteId ~= "" then
                        -- Находим название исследования по ID
                        local prerequisiteName = ""
                        for _, research in ipairs(dataCache) do
                            if research.technology and research.technology.id == prerequisiteId then
                                prerequisiteName = research.technology.name
                                break
                            end
                        end
 
                        -- Если название найдено, выводим его
                        if prerequisiteName ~= "" then
                            prerequisites = prerequisites .. '<li>{{#invoke:Ftl|main|translation|'.. prerequisiteName .. '}}</li>'
                        end
                    end
                end
                prerequisites = prerequisites .. '</ul>'
            end
 
            -- Формирование строки открываемых исследований
            local unlocks = ""
            if tech.recipeUnlocks and #tech.recipeUnlocks > 0 then
                unlocks = '<ul>'
                for _, recipe in ipairs(tech.recipeUnlocks) do
                    if recipe and recipe ~= "" then
                        unlocks = unlocks .. '<li>{{#invoke:Entity Lookup|createimagetooltip|Файл:'
                            .. recipe .. '.png|' .. recipe
                            .. '|Мета=32x32px,link=}} {{#invoke:Entity Lookup|getname|'
                            .. recipe .. '}}</li>'
                    end
                end
                unlocks = unlocks .. '</ul>'
            end
 
            -- Шаблон для отображения блока исследования
            local templateArgs = {
                id = tech.id,
                icon = iconPath,
                name = tech.name,
                discipline = tech.discipline,
                tier = tech.tier,
                tierColor = tierColor,
                disciplineName = disciplineName,
                cost = tech.cost,
                unlocks = unlocks
            }
 
            -- Добавление prerequisites только если он существует
            if prerequisites ~= "" then
                templateArgs.prerequisites = prerequisites
            end
 
            out = out .. frame:expandTemplate({
                title = 'Prototypes/Механика/Исследование',
                args = templateArgs
            })
end
        return mw.getCurrentFrame():preprocess(out)
    else
        return '<div style="color:red;">Не указан ID исследования.</div>'
     end
     end
end
end


return p
return p