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

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


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


Строка 73: Строка 67:
     })
     })


     local dataCache = loadResearchData()
     local dataCache = loadData("User:IanComradeBot/Песочница.json")
 
     if not data or type(data) ~= 'table' then
     if not dataCache or #dataCache == 0 then
         return 'Ошибка: Невозможно загрузить данные из JSON.'
         return cssLink .. '<div style="color:red;">Данные исследований не загружены или пусты.</div>'
     end
     end
 
   
     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">'


Строка 98: Строка 90:


             -- Генерация строк prerequisites и unlocks
             -- Генерация строк prerequisites и unlocks
             local prerequisitesStr = ""
             local prerequisitesStr = generateTemplate(tech.technologyPrerequisites, "prerequisite")
            if tech.technologyPrerequisites and #tech.technologyPrerequisites > 0 then
             local unlocksStr = generateTemplate(tech.recipeUnlocks, "unlock")
                prerequisitesStr = generateTemplate(tech.technologyPrerequisites, "prerequisite")
            end
 
             local unlocksStr = ""
            if tech.recipeUnlocks and #tech.recipeUnlocks > 0 then
                unlocksStr = generateTemplate(tech.recipeUnlocks, "unlock")
            end


             -- Формируем вывод с использованием шаблона
             -- Формируем вывод с использованием шаблона
Строка 125: Строка 110:
         end
         end


         out = out .. '</div>' -- Закрываем блок research-group
         out = out .. '</div>'
         return out
         return out
     else
     else

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

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

local p = {}

-- Загрузка данных
local function loadData(filePath)
    local page = mw.title.new(filePath)
    local content = page and page:getContent()
    return content and mw.text.jsonDecode(content) or nil
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"
}

-- Универсальная функция для генерации списков
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)
    -- Подключение CSS
    local cssLink = frame:extensionTag('templatestyles', '', {
        src = 'Шаблон:Research/styles.css'
    })

    local dataCache = loadData("User:IanComradeBot/Песочница.json")
    if not data or type(data) ~= 'table' then
        return 'Ошибка: Невозможно загрузить данные из JSON.'
    end
    
    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 nil

            -- Генерация строк prerequisites и unlocks
            local prerequisitesStr = generateTemplate(tech.technologyPrerequisites, "prerequisite")
            local unlocksStr = generateTemplate(tech.recipeUnlocks, "unlock")

            -- Формируем вывод с использованием шаблона
            out = out .. mw.getCurrentFrame():preprocess(
                '{{Prototypes/Механика/Исследование' ..
                '|id=' .. tech.id ..
                '|icon=' .. iconPath ..
                '|name=' .. tech.name ..
                '|discipline=' .. tech.discipline ..
                '|tier=' .. tech.tier ..
                '|tierColor=' .. tierColor ..
                '|disciplineName=' .. disciplineName ..
                '|cost=' .. tech.cost ..
                '|prerequisites=' .. prerequisitesStr ..
                '|unlocks=' .. unlocksStr ..
                '}}'
            )
        end

        out = out .. '</div>'
        return out
    else
        return cssLink .. '<div style="color:red;">Дисциплина "' .. discipline .. '" не найдена.</div>'
    end
end

return p