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

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


---------------------------------------------
-- Функция для загрузки и парсинга JSON-файла
---------------------------------------------
local function loadJSONData(pageName)
    local title = mw.title.new(pageName)
    if not title then
        return {}
    end
    local jsonData = title:getContent() or ""
    jsonData = jsonData
    local success, data = pcall(mw.text.jsonDecode, jsonData)
    if success and type(data) == "table" then
        return data
    else
        return {}
    end
end
-----------------------------------------------------------
-- Загрузка данных
-- Загрузка данных
-----------------------------------------------------------
local chemData = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data")
local latheData    = loadJSONData("User:IanComradeBot/prototypes/lathe.json")
local seedsData = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data")
local recipeData  = loadJSONData("User:IanComradeBot/prototypes/lathe/recipes.json")
local researchData = loadJSONData("User:IanComradeBot/prototypes/research.json")
local materialData = loadJSONData("User:IanComradeBot/prototypes/materials.json")
local chemData    = loadJSONData("User:IanComradeBot/chem prototypes.json")


-----------------------------------------------------------
local function kelvinToCelsius(k)
-- Функция для форматирования времени
     return k - 273.15
-----------------------------------------------------------
end
local function format_seconds_to_short_string(input_seconds)
     local minutes = math.floor(input_seconds / 60)
    local seconds = input_seconds % 60


    local minutes_part = minutes > 0 and (minutes .. " мин.") or nil
local function findSeedById(id, data)
     local seconds_part = seconds > 0 and (seconds .. " сек.") or nil
     for _, seed in ipairs(data) do
 
        if seed.id == id then
    if minutes_part and seconds_part then
            return seed
        return minutes_part .. " " .. seconds_part
         end
    elseif seconds_part then
        return seconds_part
    elseif minutes_part then
        return minutes_part
    else
         return '0 сек.'
     end
     end
    return nil
end
end


-----------------------------------------------------------
local function formatCharacteristics(seed)
-- Функция для сортировки рецептов
     local parts = {
-----------------------------------------------------------
        ("[[Гидропоника#Потенция|Потенция]]: %s"):format(seed.potency or 1),
local function sortRecipesByPriority(recipes)
        ("[[Гидропоника#Урожайность|Урожайность]]: %s"):format(seed.yield),
     table.sort(recipes, function(a, b)
        ("[[Гидропоника#Срок жизни|Срок жизни]]: %s"):format(seed.lifespan),
         local priority = { Static = 1, EMAG = 3 }
         ("[[Гидропоника#Созревание|Созревание]]: %s"):format(seed.maturation),
         local aPriority = priority[a.discipline] or 2
         ("[[Гидропоника#Производство|Производство]]: %s"):format(seed.production),
         local bPriority = priority[b.discipline] or 2
         ("[[Гидропоника#Стадии роста|Стадии роста]]: %s"):format(seed.growthStages or 6),
    }
    return table.concat(parts, '<br>')
end


         if a.isEmag ~= b.isEmag then
local function formatConditions(seed)
            return not a.isEmag
    local parts = {
         end
         ("[[Гидропоника#Потребление воды|Вода]]: %s"):format(seed.waterConsumption or 0.5),
 
        ("[[Гидропоника#Потребление нутриентов|Удобрение]]: %s"):format(seed.nutrientConsumption or 0.75),
        if aPriority == bPriority then
         ("[[Гидропоника#Оптимальная температура|Темп.]]: %.2f°C"):format(kelvinToCelsius(seed.idealHeat or 293)),
            if a.tier == b.tier then
    }
                return a.discipline < b.discipline
    return table.concat(parts, '<br>')
            end
end
            return a.tier < b.tier
        end


        return aPriority < bPriority
local function formatHarvestType(seed)
     end)
     return seed.harvestRepeat and "[[Гидропоника#Тип урожая|" .. tostring(seed.harvestRepeat) .. "]]" or "-"
end
end
 
local function formatHarvestType(seed)
-----------------------------------------------------------
     local harvestRepeat = seed.harvestRepeat
-- Основная функция модуля
    if harvestRepeat == "Repeat" then
-----------------------------------------------------------
        return "[[Гидропоника#Тип урожая|Многолетнее]]"
function p.main(frame)
     elseif harvestRepeat == "SelfHarvest" then
     local latheId = frame.args[1] or ""
         return "[[Гидропоника#Тип урожая|Самосбор]]"
     if latheId == "" then
    else
         return '<div style="color:red;">Не указан ID станка.</div>'
        return "[[Гидропоника#Тип урожая|Однолетнее]]"
     end
     end
end


     local lathe = nil
local function formatChemicals(seed)
     for _, data in ipairs(latheData) do
    if not seed.chemicals then return "-" end
         if data.id == latheId then
     local list = {}
             lathe = data
     for chemId, vals in pairs(seed.chemicals) do
             break
         local entry = chemData[chemId]
         end
        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
     end
    return "<ul>" .. table.concat(list) .. "</ul>"
end


     if not lathe then
local function formatMutations(seed, data)
        return '<div style="color:red;">Станок с ID "' .. latheId .. '" не найден.</div>'
     if not seed.mutationPrototypes then return "-" end
    end
     local list = {}
 
     for _, mu in ipairs(seed.mutationPrototypes) do
     local materialMapping = {}
        local target = findSeedById(mu, data)
     for _, material in ipairs(materialData) do
         if target and target.productPrototypes then
         if material.id then
             for _, prod in ipairs(target.productPrototypes) do
             materialMapping[material.id] = material.stackEntity or material.id or material.name
                table.insert(list, ("<li>{{Предмет|%s|link=Гидропоника#{{#invoke:Entity Lookup|getname|%s}}}}</li>"):format(prod, prod))
            end
         end
         end
     end
     end
    return "<ul>" .. table.concat(list) .. "</ul>"
end


    local chemMapping = {}
local function generateHeader()
     for id, chem in pairs(chemData) do
     return [[
        chemMapping[id] = chem.name
{| id="BOTANY" class="wikitable sortable mw-collapsible" style="width:100%;"
    end
! rowspan="2" style="width:10%;" | Плод
! rowspan="2" class="unsortable" style="width:5%;" | Семена
! rowspan="2" class="unsortable" style="width:5%;" | Растение
! colspan="3" class="unsortable" style="width:30%;" id="no-highlight" | Характеристики
! rowspan="2" class="unsortable" style="width:30%;" | Содержит вещества
! rowspan="2" style="width:20%;" | Мутации
|-
! style="width:10%;" class="unsortable" | Рост
! style="width:10%;" class="unsortable" | Условия
! style="width:5%;" class="unsortable" | Тип сбора
]]
end


    local out = ''
local function generateFooter()
     local recipes = {}
     return "|}"
end


    local function getRecipeDetails(recipeId)
function p.table(frame)
        for _, recipe in ipairs(recipeData) do
    local data = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data")
            if recipe.id == recipeId then
    local rows = {}
                return recipe
            end
        end
        return nil
    end


     local function findInResearch(recipeId)
     for _, seed in ipairs(data) do
        for _, research in ipairs(researchData) do
        local prodId = seed.productPrototypes[1]
            if research and research.recipeUnlocks then
        local seedId = seed.packetPrototype
                for _, unlock in ipairs(research.recipeUnlocks) do
        local seedName = string.format('{{#invoke:Entity Lookup|getname|%s}}', seedId)
                    if unlock == recipeId then
                        return {
                            name = research.name,
                            tier = research.tier,
                            discipline = research.discipline
                        }
                    end
                end
            end
        end
        return nil
    end


    -- Обработка staticRecipes
        local anchor  = string.format('{{anchor|%s}}', seedName)
    if lathe.Lathe and lathe.Lathe.staticRecipes then
        local fruitImg = string.format(
        for _, recipeId in ipairs(lathe.Lathe.staticRecipes) do
             '{{Предмет|%s|size=64px|vertical=1|imageTooltip=1|link=%s}}',
            local recipe = getRecipeDetails(recipeId)
             prodId, seedName
             if recipe and recipe.result then
        )
                table.insert(recipes, {
        local seedImg  = string.format(
                    result = recipe.result,
            '{{Предмет|%s|size=64px|vertical=1|imageTooltip=1|l=|link=%s}}',
                    completetime = recipe.completetime,
            seedId, seedName
                    materials = recipe.materials,
        )
                    discipline = "Static",
        local plantImg = string.format(
                    tier = 0
             '{{Предмет|%s-harvest|size=64px|l=|link=%s}}',
                })
             seedId, seedName
             elseif recipe and recipe.resultReagents then
         )
                for reagent, amount in pairs(recipe.resultReagents) do
                    local reagentName = chemMapping[reagent] or reagent
                    table.insert(recipes, {
                        result = reagentName .. "|amount=" .. amount .. "ед.|mode-chem=1",
                        completetime = recipe.completetime,
                        materials = recipe.materials,
                        discipline = "Static",
                        tier = 0
                    })
                    break
                end
             else
                out = out .. '<div style="color:red;">Ошибка: Рецепт с ID "' .. recipeId .. '" не найден или поля result/resultReagents отсутствуют.</div>'
             end
         end
    end


     -- Обработка dynamicRecipes
        local colGrowth     = formatCharacteristics(seed)
    if lathe.Lathe and lathe.Lathe.dynamicRecipes then
         local colConditions = formatConditions(seed)
         for _, recipeId in ipairs(lathe.Lathe.dynamicRecipes) do
        local colHarvest    = formatHarvestType(seed)
            local recipe = getRecipeDetails(recipeId)
        local colChemicals  = formatChemicals(seed)
            if recipe then
        local colMutations  = formatMutations(seed, data)
                local researchInfo = findInResearch(recipeId)
                if researchInfo then
                    table.insert(recipes, {
                        result = recipe.result,
                        completetime = recipe.completetime,
                        materials = recipe.materials,
                        discipline = researchInfo.discipline,
                        tier = researchInfo.tier,
                        researchName = researchInfo.name
                    })
                end
            end
        end
    end


    -- Обработка emagStaticRecipes
        local row = frame:preprocess(string.format(
    if lathe.EmagLatheRecipes and lathe.EmagLatheRecipes.emagStaticRecipes then
            [[|-
        for _, recipeId in ipairs(lathe.EmagLatheRecipes.emagStaticRecipes) do
            ! %s
             local recipe = getRecipeDetails(recipeId)
            ! %s
             if recipe then
            ! %s
                table.insert(recipes, {
            | %s
                    result = recipe.result,
            | %s
                    completetime = recipe.completetime,
             | %s
                    materials = recipe.materials,
             | %s
                    discipline = "Static",
            | %s ]],
                    tier = 0,
            fruitImg, seedImg, plantImg,
                    isEmag = true
            colGrowth, colConditions, colHarvest,
                })
            colChemicals, colMutations
            end
        ))
         end
         table.insert(rows, row)
     end
     end


     -- Обработка emagDynamicRecipes
     return generateHeader() .. table.concat(rows, '\n') .. '\n' .. generateFooter()
    if lathe.EmagLatheRecipes and lathe.EmagLatheRecipes.emagDynamicRecipes then
end
        for _, recipeId in ipairs(lathe.EmagLatheRecipes.emagDynamicRecipes) do
            local recipe = getRecipeDetails(recipeId)
            if recipe then
                local researchInfo = findInResearch(recipeId)
                if researchInfo then
                    table.insert(recipes, {
                        result = recipe.result,
                        completetime = recipe.completetime,
                        materials = recipe.materials,
                        discipline = researchInfo.discipline,
                        tier = researchInfo.tier,
                        researchName = researchInfo.name,
                        isEmag = true
                    })
                end
            end
        end
    end


     sortRecipesByPriority(recipes)
function p.main(frame)
    local args = frame.args
    local id = args[1]
    local mode  = mw.text.trim(args[2] or ""):lower()
     local seed = findSeedById(id, seedsData)
    if not seed then return "" end


     -- Таблица для перевода названий дисциплин
     if mode  == "growth" then
    local disciplineMapping = {
         return formatCharacteristics(seed)
        Arsenal = "Арсенал",
     elseif mode  == "conditions" then
         Industrial = "Промышленность",
         return formatConditions(seed)
        Experimental = "Экспериментальное",
     elseif mode  == "harvest" then
        CivilianServices = "Обслуживание персонала"
        return formatHarvestType(seed)
     }
    elseif mode  == "chemicals" then
 
        return formatChemicals(seed)
    -- Таблица для цветов по уровням
    elseif mode  == "mutations" then
    local tierColors = {
         return formatMutations(seed, seedsData)
        [1] = "#54d554",
    else
        [2] = "#ed9000",
         return ""
         [3] = "#d72a2a"
    }
 
    local materialUseMultiplier = (lathe.Lathe and lathe.Lathe.materialUseMultiplier) or 1
     local timeMultiplier = (lathe.Lathe and lathe.Lathe.timeMultiplier) or 1
 
    for _, recipe in ipairs(recipes) do
        local scaledTime = format_seconds_to_short_string(recipe.completetime * timeMultiplier)
        out = out .. '{{Шаблон:Prototypes/Машина/Станок|product=' .. recipe.result
        out = out .. '|complete-time=' .. scaledTime
        out = out .. '|materials='
 
        if type(recipe.materials) == "table" and next(recipe.materials) then
            for material, amount in pairs(recipe.materials) do
                local stackEntity = materialMapping[material] or material
                local scaledAmount = (amount * materialUseMultiplier) / 100
                out = out .. '<b>[[File:' .. stackEntity .. '.png|32x32px|link=]] ' .. scaledAmount .. ' {{#invoke:Entity Lookup|getname|' .. stackEntity .. '}}</b>'
            end
        else
            out = out .. 'Нет данных о материалах'
        end
 
        -- Информация об исследовании
        if recipe.discipline ~= "Static" then
            local tierColor = tierColors[recipe.tier] or "#FFFFFF"
            local disciplineName = disciplineMapping[recipe.discipline] or "Неизвестная дисциплина"
 
            out = out .. '|info=<div style="font-weight:600;"><span style="margin:8px;">[[File:' .. recipe.discipline .. '.png|16x16px|link=]]</span> [[Руководство по исследованию и разработке|' .. disciplineName
            out = out .. ']], уровень: <span style="color: ' .. tierColor .. '">' .. recipe.tier .. '</span> </div>'
        end
 
        -- Пометка при взломе EMAG
        if recipe.isEmag then
            out = out .. '|mode-emag=1'
         end
 
         -- Пометка для исследуемой технологии
        if recipe.discipline ~= "Static" then
            out = out .. '|mode-research=1'
        end
 
        out = out .. '}}'
     end
     end
    return mw.getCurrentFrame():preprocess(out)
end
end


return p
return p

Текущая версия от 23:43, 26 ноября 2025

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

local p = {}

-- Загрузка данных
local chemData = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data")
local seedsData = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data")

local function kelvinToCelsius(k)
    return k - 273.15
end

local function findSeedById(id, data)
    for _, seed in ipairs(data) do
        if seed.id == id then
            return seed
        end
    end
    return nil
end

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

local function formatConditions(seed)
    local parts = {
        ("[[Гидропоника#Потребление воды|Вода]]: %s"):format(seed.waterConsumption or 0.5),
        ("[[Гидропоника#Потребление нутриентов|Удобрение]]: %s"):format(seed.nutrientConsumption or 0.75),
        ("[[Гидропоника#Оптимальная температура|Темп.]]: %.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

local function formatMutations(seed, data)
    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
    return "<ul>" .. table.concat(list) .. "</ul>"
end

local function generateHeader()
    return [[
{| id="BOTANY" class="wikitable sortable mw-collapsible" style="width:100%;"
! rowspan="2" style="width:10%;" | Плод
! rowspan="2" class="unsortable" style="width:5%;" | Семена
! rowspan="2" class="unsortable" style="width:5%;" | Растение
! colspan="3" class="unsortable" style="width:30%;" id="no-highlight" | Характеристики
! rowspan="2" class="unsortable" style="width:30%;" | Содержит вещества
! rowspan="2" style="width:20%;" | Мутации
|- 
! style="width:10%;" class="unsortable" | Рост
! style="width:10%;" class="unsortable" | Условия
! style="width:5%;" class="unsortable" | Тип сбора
]]
end

local function generateFooter()
    return "|}"
end

function p.table(frame)
    local data = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data")
    local rows = {}

    for _, seed in ipairs(data) do
        local prodId = seed.productPrototypes[1]
        local seedId = seed.packetPrototype
        local seedName = string.format('{{#invoke:Entity Lookup|getname|%s}}', seedId)

        local anchor   = string.format('{{anchor|%s}}', seedName)
        local fruitImg = string.format(
            '{{Предмет|%s|size=64px|vertical=1|imageTooltip=1|link=%s}}',
            prodId, seedName
        )
        local seedImg  = string.format(
            '{{Предмет|%s|size=64px|vertical=1|imageTooltip=1|l=|link=%s}}',
            seedId, seedName
        )
        local plantImg = string.format(
            '{{Предмет|%s-harvest|size=64px|l=|link=%s}}',
            seedId, seedName
        )

        local colGrowth     = formatCharacteristics(seed)
        local colConditions = formatConditions(seed)
        local colHarvest    = formatHarvestType(seed)
        local colChemicals  = formatChemicals(seed)
        local colMutations  = formatMutations(seed, data)

        local row = frame:preprocess(string.format(
            [[|-
            ! %s 
            ! %s 
            ! %s 
            | %s 
            | %s 
            | %s 
            | %s 
            | %s ]],
            fruitImg, seedImg, plantImg,
            colGrowth, colConditions, colHarvest,
            colChemicals, colMutations
        ))
        table.insert(rows, row)
    end

    return generateHeader() .. table.concat(rows, '\n') .. '\n' .. generateFooter()
end

function p.main(frame)
    local args = frame.args
    local id = args[1]
    local mode  = mw.text.trim(args[2] or ""):lower()
    local seed = findSeedById(id, seedsData)
    if not seed then return "" end

    if mode  == "growth" then
        return formatCharacteristics(seed)
    elseif mode  == "conditions" then
        return formatConditions(seed)
    elseif mode  == "harvest" then
        return formatHarvestType(seed)
    elseif mode  == "chemicals" then
        return formatChemicals(seed)
    elseif mode  == "mutations" then
        return formatMutations(seed, seedsData)
    else
        return ""
    end
end

return p