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

Материал из Space Station 14 Вики
мНет описания правки
Нет описания правки
Строка 1: Строка 1:
local p = {}
local p = {}


-- Функция для загрузки данных исследований из JSON-файла
local function loadResearchData()
local function loadResearchData()
     local jsonContent = mw.title.new("User:IanComradeBot/Песочница.json"):getContent()
     local jsonContent = mw.title.new("User:IanComradeBot/Песочница.json"):getContent()
Строка 39: Строка 40:
}
}


-- Универсальная функция для генерации списков
-- Функция для обработки вывода
local function generateTemplate(list, templateType)
    if not list or #list == 0 then
        return ""
    end
 
    local result = "<ul>"
    for _, entry in ipairs(list) do
        if entry and entry ~= "" then
            if templateType == "prerequisite" then
                result = result .. '<li>{{#invoke:Entity Lookup|createimagetooltip|Файл:'
                    .. entry .. '.png|' .. entry
                    .. '|Мета=32x32px,link=}} '
                    .. entry .. '</li>'
            elseif templateType == "unlock" then
                result = result .. '<li>{{#invoke:Entity Lookup|createimagetooltip|Файл:'
                    .. entry .. '.png|' .. entry
                    .. '|Мета=32x32px,link=}} {{#invoke:Entity Lookup|getname|'
                    .. entry .. '}}</li>'
            end
        end
    end
    result = result .. "</ul>"
 
    return result
end
 
function p.main(frame)
function p.main(frame)
     -- Подключение CSS
     -- Подключение CSS
Строка 72: Строка 47:
     })
     })


    -- Загрузка данных из JSON
     local dataCache = loadResearchData()
     local dataCache = loadResearchData()
     local discipline = frame.args[1] or ""
     local discipline = frame.args[1] or ""


     if discipline and discipline ~= "" then
     if discipline and discipline ~= "" then
        -- Инициализация строки вывода
         local out = cssLink .. '<div class="research-group">'
         local out = cssLink .. '<div class="research-group">'


Строка 85: Строка 62:
         end
         end


        -- Перебор всех исследований и формирование их вывода
         for _, tech in ipairs(researches) do
         for _, tech in ipairs(researches) do
             local disciplineName = disciplineMapping[tech.discipline] or "Неизвестная дисциплина"
             local disciplineName = disciplineMapping[tech.discipline] or "Неизвестная дисциплина"
             local tierColor = tierColors[tech.tier] or "#FFFFFF"
             local tierColor = tierColors[tech.tier] or "#FFFFFF"
             local iconPath = tech.icon and tech.icon.sprite or nil
             local iconPath = tech.icon and tech.icon.sprite or ""
 
            -- Формирование строки prerequisites
            local prerequisitesStr = ""
            if tech.technologyPrerequisites and #tech.technologyPrerequisites > 0 then
                prerequisitesStr = '<ul>'
                for _, prerequisite in ipairs(tech.technologyPrerequisites) do
                    if prerequisite and prerequisite ~= "" then
                        prerequisitesStr = prerequisitesStr .. '<li>' .. mw.text.encode(prerequisite) .. '</li>'
                    end
                end
                prerequisitesStr = prerequisitesStr .. '</ul>'
            end


             -- Генерация строк prerequisites и unlocks
             -- Формирование строки unlocks
             local prerequisitesStr = generateTemplate(tech.technologyPrerequisites, "prerequisite")
             local unlocksStr = ""
             local unlocksStr = generateTemplate(tech.recipeUnlocks, "unlock")
             if tech.recipeUnlocks and #tech.recipeUnlocks > 0 then
                unlocksStr = '<ul>'
                for _, recipe in ipairs(tech.recipeUnlocks) do
                    if recipe and recipe ~= "" then
                        unlocksStr = unlocksStr .. '<li>' .. mw.text.encode(recipe) .. '</li>'
                    end
                end
                unlocksStr = unlocksStr .. '</ul>'
            end


             -- Формируем вывод с использованием шаблона
             -- Формируем строку с использованием шаблона
             out = out ..
             local templateCall = '{{Prototypes/Механика/Исследование' ..
                '{{Prototypes/Механика/Исследование' ..
                 '|id=' .. (tech.id or "") ..
                 '|id=' .. tech.id ..
                 '|icon=' .. (iconPath or "") ..
                 '|icon=' .. iconPath ..
                 '|name=' .. (tech.name or "") ..
                 '|name=' .. tech.name ..
                 '|discipline=' .. (tech.discipline or "") ..
                 '|discipline=' .. tech.discipline ..
                 '|tier=' .. (tech.tier or 0) ..
                 '|tier=' .. tech.tier ..
                 '|tierColor=' .. (tierColor or "#FFFFFF") ..
                 '|tierColor=' .. tierColor ..
                 '|disciplineName=' .. (disciplineName or "") ..
                 '|disciplineName=' .. disciplineName ..
                 '|cost=' .. (tech.cost or 0) ..
                 '|cost=' .. tech.cost ..
                 '|prerequisites=' .. (prerequisitesStr or "") ..
                 '|prerequisites=' .. prerequisitesStr ..
                 '|unlocks=' .. (unlocksStr or "") ..
                 '|unlocks=' .. unlocksStr ..
                 '}}'
                 '}}'
              
 
             -- Печатаем шаблон в вывод
            out = out .. templateCall
         end
         end
 
       
         out = out .. '</div>'
         out = out .. '</div>' -- Закрываем div
         return out
         return out
     else
     else

Версия от 21:34, 25 января 2025

Для документации этого модуля может быть создана страница Модуль:Песочница/Pok/doc

local p = {}

-- Функция для загрузки данных исследований из JSON-файла
local function loadResearchData()
    local jsonContent = mw.title.new("User:IanComradeBot/Песочница.json"):getContent()
    if not jsonContent or jsonContent == "" then
        error("Не удалось загрузить содержимое JSON-файла.")
    end
    local success, data = pcall(mw.text.jsonDecode, jsonContent)
    if not success then
        error("Ошибка декодирования JSON: " .. tostring(data))
    end
    return data
end

-- Функция для поиска исследований по дисциплине
local function findResearchByDiscipline(dataCache, discipline)
    local results = {}
    for _, research in ipairs(dataCache) do
        if research.technology and research.technology.discipline == discipline then
            table.insert(results, research.technology)
        end
    end
    return results
end

-- Таблица для перевода названий дисциплин
local disciplineMapping = {
    Arsenal = "Арсенал",
    Industrial = "Промышленность",
    Experimental = "Экспериментальное",
    CivilianServices = "Обслуживание персонала"
}

-- Таблица для цветов по уровням
local tierColors = {
    [1] = "#54d554",
    [2] = "#ed9000",
    [3] = "#d72a2a"
}

-- Функция для обработки вывода
function p.main(frame)
    -- Подключение CSS
    local cssLink = frame:extensionTag('templatestyles', '', {
        src = 'Шаблон:Research/styles.css'
    })

    -- Загрузка данных из JSON
    local dataCache = loadResearchData()
    local discipline = frame.args[1] or ""

    if discipline and discipline ~= "" then
        -- Инициализация строки вывода
        local out = cssLink .. '<div class="research-group">'

        -- Получаем список исследований по дисциплине
        local researches = findResearchByDiscipline(dataCache, discipline)

        if #researches == 0 then
            out = out .. '<div style="color:red;">Нет исследований для дисциплины "' .. discipline .. '"</div>'
        end

        -- Перебор всех исследований и формирование их вывода
        for _, tech in ipairs(researches) do
            local disciplineName = disciplineMapping[tech.discipline] or "Неизвестная дисциплина"
            local tierColor = tierColors[tech.tier] or "#FFFFFF"
            local iconPath = tech.icon and tech.icon.sprite or ""

            -- Формирование строки prerequisites
            local prerequisitesStr = ""
            if tech.technologyPrerequisites and #tech.technologyPrerequisites > 0 then
                prerequisitesStr = '<ul>'
                for _, prerequisite in ipairs(tech.technologyPrerequisites) do
                    if prerequisite and prerequisite ~= "" then
                        prerequisitesStr = prerequisitesStr .. '<li>' .. mw.text.encode(prerequisite) .. '</li>'
                    end
                end
                prerequisitesStr = prerequisitesStr .. '</ul>'
            end

            -- Формирование строки unlocks
            local unlocksStr = ""
            if tech.recipeUnlocks and #tech.recipeUnlocks > 0 then
                unlocksStr = '<ul>'
                for _, recipe in ipairs(tech.recipeUnlocks) do
                    if recipe and recipe ~= "" then
                        unlocksStr = unlocksStr .. '<li>' .. mw.text.encode(recipe) .. '</li>'
                    end
                end
                unlocksStr = unlocksStr .. '</ul>'
            end

            -- Формируем строку с использованием шаблона
            local templateCall = '{{Prototypes/Механика/Исследование' ..
                '|id=' .. (tech.id or "") ..
                '|icon=' .. (iconPath or "") ..
                '|name=' .. (tech.name or "") ..
                '|discipline=' .. (tech.discipline or "") ..
                '|tier=' .. (tech.tier or 0) ..
                '|tierColor=' .. (tierColor or "#FFFFFF") ..
                '|disciplineName=' .. (disciplineName or "") ..
                '|cost=' .. (tech.cost or 0) ..
                '|prerequisites=' .. (prerequisitesStr or "") ..
                '|unlocks=' .. (unlocksStr or "") ..
                '}}'

            -- Печатаем шаблон в вывод
            out = out .. templateCall
        end
        
        out = out .. '</div>' -- Закрываем div
        return out
    else
        return cssLink .. '<div style="color:red;">Дисциплина "' .. discipline .. '" не найдена.</div>'
    end
end

return p