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

Материал из Space Station 14 Вики
мНет описания правки
Нет описания правки
 
(не показано 380 промежуточных версий этого же участника)
Строка 1: Строка 1:
local p = {}
local p = {}
local getArgs = require('Module:Arguments').getArgs


local function loadResearchData()
function p.main(frame)
     local jsonContent = mw.title.new("User:IanComradeBot/Песочница.json"):getContent()
     local args = getArgs(frame, { removeBlanks = false })
     if not jsonContent or jsonContent == "" then
    local name = args[1] or ""
         error("Не удалось загрузить содержимое JSON-файла.")
    local attributes = args[2] or ""
     if name == "" then
         return "<span class=\"error\">Ошибка: не указано имя файла.</span>"
     end
     end
     local success, data = pcall(mw.text.jsonDecode, jsonContent)
     local ext = (args["ext"] or "png"):gsub("^%.", "")
     if not success then
    local namespace = args["namespace"] or "Файл"
         error("Ошибка декодирования JSON: " .. tostring(data))
    local max = tonumber(args["max"]) or 50
    local include_base = (args["base"] ~= "no")
 
    local found = {}
 
     if include_base then
         local t = mw.title.new("Файл:" .. name .. "." .. ext)
        if t and t.exists then
            table.insert(found, "")
        end
     end
     end
    return data
end


-- Функция для поиска исследований по дисциплине
    for i = 1, max do
local function findResearchByDiscipline(dataCache, discipline)
        local t = mw.title.new("Файл:" .. name .. "-" .. i .. "." .. ext)
    local results = {}
         if t and t.exists then
    for _, research in ipairs(dataCache) do
             table.insert(found, "-" .. i)
         if research.technology and research.technology.discipline == discipline then
             table.insert(results, research.technology)
         end
         end
     end
     end
    return results
end


-- Таблица для перевода названий дисциплин
     if #found == 0 then
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 ""
         return ""
     end
     end


     local result = "<ul>"
     local before = "[[" .. namespace .. ":" .. name
    for _, entry in ipairs(list) do
    local after = "." .. ext .. "|" .. attributes .. "]]"
        if entry and entry ~= "" then
 
            if templateType == "prerequisite" then
    local parts = {}
                result = result .. '<li>{{#invoke:Entity Lookup|createimagetooltip|Файл:'
    table.insert(parts, "<choose before=\"" .. before .. "\" after=\"" .. after .. "\">")
                    .. entry .. '.png|' .. entry
    for _, suf in ipairs(found) do
                    .. '|Мета=32x32px,link=}} '
        table.insert(parts, "<option>" .. suf .. "</option>")
                    .. 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
     end
     result = result .. "</ul>"
     table.insert(parts, "</choose>")


     return result
     return frame:preprocess(table.concat(parts, "\n"))
end
 
function p.main(frame)
    -- Подключение CSS
    local cssLink = frame:extensionTag('templatestyles', '', {
        src = 'Шаблон:Research/styles.css'
    })
 
    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 nil
 
            -- Генерация строк prerequisites и unlocks
            local prerequisitesStr = generateTemplate(tech.technologyPrerequisites, "prerequisite")
            local unlocksStr = generateTemplate(tech.recipeUnlocks, "unlock")
 
            -- Формируем вывод с использованием шаблона
            out = out ..
                '{{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
end


return p
return p

Текущая версия от 02:52, 17 марта 2026

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

local p = {}
local getArgs = require('Module:Arguments').getArgs

function p.main(frame)
    local args = getArgs(frame, { removeBlanks = false })
    local name = args[1] or ""
    local attributes = args[2] or ""
    if name == "" then
        return "<span class=\"error\">Ошибка: не указано имя файла.</span>"
    end
    local ext = (args["ext"] or "png"):gsub("^%.", "") 
    local namespace = args["namespace"] or "Файл"
    local max = tonumber(args["max"]) or 50
    local include_base = (args["base"] ~= "no")

    local found = {}

    if include_base then
        local t = mw.title.new("Файл:" .. name .. "." .. ext)
        if t and t.exists then
            table.insert(found, "")
        end
    end

    for i = 1, max do
        local t = mw.title.new("Файл:" .. name .. "-" .. i .. "." .. ext)
        if t and t.exists then
            table.insert(found, "-" .. i)
        end
    end

    if #found == 0 then
        return ""
    end

    local before = "[[" .. namespace .. ":" .. name
    local after = "." .. ext .. "|" .. attributes .. "]]"

    local parts = {}
    table.insert(parts, "<choose before=\"" .. before .. "\" after=\"" .. after .. "\">")
    for _, suf in ipairs(found) do
        table.insert(parts, "<option>" .. suf .. "</option>")
    end
    table.insert(parts, "</choose>")

    return frame:preprocess(table.concat(parts, "\n"))
end

return p