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

мНет описания правки
мНет описания правки
 
(не показано 230 промежуточных версий этого же участника)
Строка 1: Строка 1:
local p = {}
local p = {}


-- Функция для загрузки данных исследований из JSON-файла
-- Загрузка данных
local function loadResearchData()
local chemData = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data")
    return mw.text.jsonDecode(mw.title.new("User:IanComradeBot/prototypes/research.json"):getContent())
local seedsData = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data")
 
local function kelvinToCelsius(k)
    return k - 273.15
end
end


-- Таблица для перевода названий дисциплин
local function findSeedById(id, data)
local disciplineMapping = {
     for _, seed in ipairs(data) do
     Arsenal = "Арсенал",
        if seed.id == id then
    Industrial = "Промышленность",
            return seed
     Experimental = "Экспериментальное",
        end
     CivilianServices = "Обслуживание персонала"
     end
}
     return nil
end


-- Таблица для цветов по уровням
local function formatCharacteristics(seed)
local tierColors = {
    local parts = {
    [1] = "#54d554",
        ("[[Гидропоника#Потенция|Потенция]]: %s"):format(seed.potency or 1),
    [2] = "#ed9000",
        ("[[Гидропоника#Урожайность|Урожайность]]: %s"):format(seed.yield),
    [3] = "#d72a2a"
        ("[[Гидропоника#Срок жизни|Срок жизни]]: %s"):format(seed.lifespan),
}
        ("[[Гидропоника#Созревание|Созревание]]: %s"):format(seed.maturation),
        ("[[Гидропоника#Производство|Производство]]: %s"):format(seed.production),
        ("[[Гидропоника#Стадии роста|Стадии роста]]: %s"):format(seed.growthStages or 6),
    }
    return table.concat(parts, '<br>')
end


function p.main(frame)
local function formatConditions(seed)
     local dataCache = loadResearchData()
     local parts = {
     local input = frame.args[1] or ""
        ("[[Гидропоника#Потребление воды|Вода]]: %s"):format(seed.waterConsumption or 0.5),
     local manualIcon = frame.args[2] or ""
        ("[[Гидропоника#Потребление нутриентов|Удобрение]]: %s"):format(seed.nutrientConsumption or 0.75),
     local out = ""
        ("[[Гидропоника#Оптимальная температура|Темп.]]: %.2f°C"):format(kelvinToCelsius(seed.idealHeat or 293)),
    }
     return table.concat(parts, '<br>')
end
 
local function formatHarvestType(seed)
    return seed.harvestRepeat and "[[Гидропоника#Тип урожая|" .. tostring(seed.harvestRepeat) .. "]]" or "-"
end
local function formatHarvestType(seed)
     local harvestRepeat = seed.harvestRepeat
    if harvestRepeat == "Repeat" then
        return "[[Гидропоника#Тип урожая|Многолетнее]]"
    elseif harvestRepeat == "SelfHarvest" then
        return "[[Гидропоника#Тип урожая|Самосбор]]"
    else
        return "[[Гидропоника#Тип урожая|Однолетнее]]"
    end
end
 
local function formatChemicals(seed)
    if not seed.chemicals then return "-" end
     local list = {}
    for chemId, vals in pairs(seed.chemicals) do
        local entry = chemData[chemId]
        local chemName = entry and entry.name or chemId
        table.insert(list, string.format(
            "<li>[[Химия#chem_%s|%s]] (мин: %s, макс: %s, дел: %s)</li>",
            chemId, chemName, vals.Min or 0, vals.Max or 0, vals.PotencyDivisor or 1
        ))
    end
    return "<ul>" .. table.concat(list) .. "</ul>"
end


     if input == "" then
local function formatMutations(seed, data)
        return '<div style="color:red;">Не указан идентификатор исследования или дисциплина.</div>'
     if not seed.mutationPrototypes then return "-" end
    local list = {}
    for _, mu in ipairs(seed.mutationPrototypes) do
        local target = findSeedById(mu, data)
        if target and target.productPrototypes then
            for _, prod in ipairs(target.productPrototypes) do
                table.insert(list, ("<li>{{Предмет|%s|link=Гидропоника#{{#invoke:Entity Lookup|getname|%s}}}}</li>"):format(prod, prod))
            end
        end
     end
     end
    return "<ul>" .. table.concat(list) .. "</ul>"
end


    -- Если первый параметр соответствует дисциплине, работаем в режиме категории
local function generateHeader()
     if disciplineMapping[input] then
     return [[
        local found = false
{| id="BOTANY" class="wikitable sortable mw-collapsible" style="width:100%;"
        for _, research in ipairs(dataCache) do
! rowspan="2" style="width:10%;" | Плод
            if research.technology and research.technology.discipline == input then
! rowspan="2" class="unsortable" style="width:5%;" | Семена
                found = true
! rowspan="2" class="unsortable" style="width:5%;" | Растение
                local tech = research.technology
! colspan="3" class="unsortable" style="width:30%;" id="no-highlight" | Характеристики
                local iconPath = tech.icon and tech.icon.sprite or nil  -- иконка берётся из tech.icon.sprite
! rowspan="2" class="unsortable" style="width:30%;" | Содержит вещества
                local tierColor = tierColors[tech.tier] or "#FFFFFF"
! rowspan="2" style="width:20%;" | Мутации
                local disciplineName = disciplineMapping[tech.discipline] or "Неизвестная дисциплина"
|-  
! style="width:10%;" class="unsortable" | Рост
! style="width:10%;" class="unsortable" | Условия
! style="width:5%;" class="unsortable" | Тип сбора
]]
end


                -- Формирование строки необходимых исследований (prerequisites)
local function generateFooter()
                local prerequisites = ""
    return "|}"
                if tech.technologyPrerequisites and #tech.technologyPrerequisites > 0 then
end
                    prerequisites = '<ul>'
                    for _, prerequisiteId in ipairs(tech.technologyPrerequisites) do
                        if prerequisiteId and prerequisiteId ~= "" then
                            local prerequisiteName = ""
                            for _, r in ipairs(dataCache) do
                                if r.technology and r.technology.id == prerequisiteId then
                                    prerequisiteName = r.technology.name
                                    break
                                end
                            end
                            if prerequisiteName ~= "" then
                                prerequisites = prerequisites .. '<li>{{#invoke:Ftl|main|translation|' .. prerequisiteName .. '}}</li>'
                            end
                        end
                    end
                    prerequisites = prerequisites .. '</ul>'
                end


                -- Формирование строки открываемых исследований (unlocks)
function p.table(frame)
                local unlocks = ""
    local data = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data")
                if tech.recipeUnlocks and #tech.recipeUnlocks > 0 then
    local rows = {}
                    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 = {
    for _, seed in ipairs(data) do
                    id = tech.id,
        local prodId = seed.productPrototypes[1]
                    icon = iconPath,
        local seedId = seed.packetPrototype
                    name = tech.name,
        local seedName = string.format('{{#invoke:Entity Lookup|getname|%s}}', seedId)
                    discipline = tech.discipline,
                    tier = tech.tier,
                    tierColor = tierColor,
                    disciplineName = disciplineName,
                    cost = tech.cost,
                    unlocks = unlocks
                }
                if prerequisites ~= "" then
                    templateArgs.prerequisites = prerequisites
                end


                out = out .. frame:expandTemplate({
        local anchor  = string.format('{{anchor|%s}}', seedName)
                    title = 'Prototypes/Механика/Исследование',
        local fruitImg = string.format(
                    args = templateArgs
            '{{Предмет|%s|size=64px|vertical=1|imageTooltip=1|link=%s}}',
                })
             prodId, seedName
             end
         )
         end
         local seedImg  = string.format(
         if not found then
             '{{Предмет|%s|size=64px|vertical=1|imageTooltip=1|l=|link=%s}}',
             out = out .. '<div style="color:red;">Не найдено исследований для дисциплины "' .. input .. '".</div>'
            seedId, seedName
        end
         )
         return mw.getCurrentFrame():preprocess(out)
         local plantImg = string.format(
    else
             '{{Предмет|%s-harvest|size=64px|l=|link=%s}}',
        -- Режим поиска по ID исследования
             seedId, seedName
         local tech = nil
         )
        for _, research in ipairs(dataCache) do
             if research.technology and research.technology.id == input then
                tech = research.technology
                break
             end
         end


         if not tech then
         local colGrowth    = formatCharacteristics(seed)
            out = out .. '<div style="color:red;">Исследование с ID "' .. input .. '" не найдено.</div>'
        local colConditions = formatConditions(seed)
         else
         local colHarvest    = formatHarvestType(seed)
            local tierColor = tierColors[tech.tier] or "#FFFFFF"
        local colChemicals  = formatChemicals(seed)
            local disciplineName = disciplineMapping[tech.discipline] or "Неизвестная дисциплина"
        local colMutations  = formatMutations(seed, data)
            -- Если иконка задана вручную, используем её, иначе берём из tech.icon.sprite
            local iconPath = manualIcon ~= "" and manualIcon or (tech.icon and tech.icon.sprite or nil)


            local prerequisites = ""
        local row = frame:preprocess(string.format(
            if tech.technologyPrerequisites and #tech.technologyPrerequisites > 0 then
            [[|-
                prerequisites = '<ul>'
            ! %s
                for _, prerequisiteId in ipairs(tech.technologyPrerequisites) do
            ! %s
                    if prerequisiteId and prerequisiteId ~= "" then
            ! %s
                        local prerequisiteName = ""
            | %s
                        for _, research in ipairs(dataCache) do
            | %s
                            if research.technology and research.technology.id == prerequisiteId then
            | %s
                                prerequisiteName = research.technology.name
            | %s
                                break
            | %s ]],
                            end
            fruitImg, seedImg, plantImg,
                        end
            colGrowth, colConditions, colHarvest,
                        if prerequisiteName ~= "" then
            colChemicals, colMutations
                            prerequisites = prerequisites .. '<li>{{#invoke:Ftl|main|translation|' .. prerequisiteName .. '}}</li>'
        ))
                        end
        table.insert(rows, row)
                    end
    end
                end
                prerequisites = prerequisites .. '</ul>'
            end


            local unlocks = ""
    return generateHeader() .. table.concat(rows, '\n') .. '\n' .. generateFooter()
            if tech.recipeUnlocks and #tech.recipeUnlocks > 0 then
end
                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 = {
function p.main(frame)
                id = tech.id,
    local args = frame.args
                icon = iconPath,
    local id = args[1]
                name = tech.name,
    local mode  = mw.text.trim(args[2] or ""):lower()
                discipline = tech.discipline,
    local seed = findSeedById(id, seedsData)
                tier = tech.tier,
    if not seed then return "" end
                tierColor = tierColor,
                disciplineName = disciplineName,
                cost = tech.cost,
                unlocks = unlocks
            }
            if prerequisites ~= "" then
                templateArgs.prerequisites = prerequisites
            end


            out = out .. frame:expandTemplate({
    if mode  == "growth" then
                title = 'Prototypes/Механика/Исследование',
        return formatCharacteristics(seed)
                args = templateArgs
    elseif mode  == "conditions" then
            })
        return formatConditions(seed)
        end
    elseif mode  == "harvest" then
         return mw.getCurrentFrame():preprocess(out)
        return formatHarvestType(seed)
    elseif mode  == "chemicals" then
         return formatChemicals(seed)
    elseif mode  == "mutations" then
        return formatMutations(seed, seedsData)
    else
        return ""
     end
     end
end
end


return p
return p