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

Материал из Space Station 14 Вики
мНет описания правки
Нет описания правки
 
(не показано 415 промежуточных версий этого же участника)
Строка 1: Строка 1:
local p = {}
local p = {}
 
local getArgs = require('Module:Arguments').getArgs
-- Функция для загрузки данных исследований из JSON-файла
local function loadResearchData()
local content = mw.title.new("User:IanComradeBot/Песочница.json"):getContent()
if not content then
return nil
end
return mw.text.jsonDecode(content)
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)
function p.main(frame)
-- Подключение CSS
    local args = getArgs(frame, { removeBlanks = false })
local cssLink = frame:extensionTag('templatestyles', '', {
    local name = args[1] or ""
src = 'Шаблон:Research/styles.css'
    local attributes = args[2] or ""
})
    if name == "" then
 
        return "<span class=\"error\">Ошибка: не указано имя файла.</span>"
-- Загрузка данных
    end
local dataCache = loadResearchData()
    local ext = (args["ext"] or "png"):gsub("^%.", "")  
if not dataCache then
    local namespace = args["namespace"] or "Файл"
return cssLink .. '<div style="color:red;">Ошибка загрузки данных исследований. Проверьте файл JSON.</div>'
    local max = tonumber(args["max"]) or 50
end
    local include_base = (args["base"] ~= "no")
 
-- Получение дисциплины
local discipline = frame.args[1] or ""
if discipline == "" then
return cssLink .. '<div style="color:red;">Не указана дисциплина. Доступные дисциплины: '
.. table.concat(vim.tbl_keys(disciplineMapping), ", ") .. '</div>'
end
 
-- Инициализация строки вывода
local out = cssLink .. '<div class="research-group">'
 
-- Получаем список исследований по дисциплине
local researches = findResearchByDiscipline(dataCache, discipline)
if not researches or #researches == 0 then
return out .. '<div style="color:red;">Нет исследований для дисциплины "' .. discipline .. '"</div></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
 
-- Проверка данных
if not tech.id or not tech.name then
return cssLink .. '<div style="color:red;">Ошибка: отсутствует ID или имя технологии.</div>'
end
 
-- Основной блок исследования
out = out .. '<div class="research" id="' .. tech.id .. '">'
out = out .. frame:preprocess('<div class="research__images">[[Файл:{{#invoke:Entity Sprite|main|path|' .. (iconPath or "default_icon.png") .. '}}]]</div>')
out = out .. frame:preprocess('<div class="research__name">{{#invoke:Ftl|main|translation|' .. tech.name .. '}}[[Файл:' .. tech.discipline .. '.png|16px|link=]]</div>')
out = out .. '<div class="research__type">'
out = out .. '<div>Уровень: <span style="color:' .. tierColor .. ';">' .. (tech.tier or "N/A") .. '</span></div>'
out = out .. '<div class="research__technology">' .. disciplineName .. '</div>'
out = out .. '<div>Стоимость: <span style="color:#DA70D6;">' .. (tech.cost or "N/A") .. '</span></div>'
out = out .. '</div>'


-- Блок необходимых исследований
    local found = {}
if tech.technologyPrerequisites and #tech.technologyPrerequisites > 0 then
out = out .. '<div class="research__technologies-prerequisites">Необходимые исследования:'
out = out .. '<ul>'


for _, prerequisite in ipairs(tech.technologyPrerequisites) do
    if include_base then
out = out .. frame:preprocess('<li>{{#invoke:Entity Lookup|getname|' .. prerequisite .. '}}</li>')
        local t = mw.title.new("Файл:" .. name .. "." .. ext)
end
        if t and t.exists then
            table.insert(found, "")
        end
    end


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


-- Блок открываемых рецептов
    if #found == 0 then
if tech.recipeUnlocks and #tech.recipeUnlocks > 0 then
        return ""
out = out .. '<div class="research__technologies-unlocks">Разблокирует:'
    end
out = out .. '<ul>'


for _, recipe in ipairs(tech.recipeUnlocks) do
    local before = "[[" .. namespace .. ":" .. name
out = out .. frame:preprocess('<li>{{#invoke:Entity Lookup|getname|' .. recipe .. '}}</li>')
    local after = "." .. ext .. "|" .. attributes .. "]]"
end
out = out .. '</ul>'
out = out .. '</div>'
end


out = out .. '</div>'
    local parts = {}
end
    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>")


out = out .. '</div>'
    return frame:preprocess(table.concat(parts, "\n"))
return out
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