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

Нет описания правки
мНет описания правки
 
(не показано 177 промежуточных версий этого же участника)
Строка 1: Строка 1:
local p = {}
-- Загрузка данных
-- Загрузка данных
local latheData    = mw.loadData("Module:IanComradeBot/prototypes/lathe.json/data")
local chemData = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data")
local recipeData  = mw.loadData("Module:IanComradeBot/prototypes/lathe/recipes.json/data")
local seedsData = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data")
local researchData = mw.loadData("Module:IanComradeBot/prototypes/research.json/data")
local materialData = mw.loadData("Module:IanComradeBot/prototypes/materials.json/data")
local chemData    = mw.loadData("Module:IanComradeBot/chem prototypes.json/data")


-- Если данные материалов не загружены корректно, добавляем отладку
local function kelvinToCelsius(k)
if type(materialData) ~= "table" or not next(materialData) then
     return k - 273.15
     mw.log("Материалов не загружено или получены пустые данные. Проверьте Module:IanComradeBot/prototypes/materials.json/data")
end
end


local p = {}
local function findSeedById(id, data)
 
     for _, seed in ipairs(data) do
-- Функция для форматирования времени
        if seed.id == id then
local function format_seconds_to_short_string(input_seconds)
            return seed
     local minutes = math.floor(input_seconds / 60)
         end
    local seconds = input_seconds % 60
 
    local minutes_part = minutes > 0 and (minutes .. " мин.") or nil
    local seconds_part = seconds > 0 and (seconds .. " сек.") or nil
 
    if minutes_part and seconds_part then
        return minutes_part .. " " .. seconds_part
    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 function sortRecipesByPriority(recipes)
     local parts = {
     table.sort(recipes, function(a, b)
        ("[[Гидропоника#Потенция|Потенция]]: %s"):format(seed.potency or 1),
         local priority = { Static = 1, EMAG = 3 }
        ("[[Гидропоника#Урожайность|Урожайность]]: %s"):format(seed.yield),
         local aPriority = priority[a.discipline] or 2
        ("[[Гидропоника#Срок жизни|Срок жизни]]: %s"):format(seed.lifespan),
         local bPriority = priority[b.discipline] or 2
         ("[[Гидропоника#Созревание|Созревание]]: %s"):format(seed.maturation),
         ("[[Гидропоника#Производство|Производство]]: %s"):format(seed.production),
         ("[[Гидропоника#Стадии роста|Стадии роста]]: %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)
function p.main(frame)
     local harvestRepeat = seed.harvestRepeat
    -- Подключение CSS
     if harvestRepeat == "Repeat" then
     local cssLink = frame:extensionTag('templatestyles', '', {
        return "[[Гидропоника#Тип урожая|Многолетнее]]"
        src = 'Шаблон:Prototypes/Машина/Станок/styles.css'
     elseif harvestRepeat == "SelfHarvest" then
     })
         return "[[Гидропоника#Тип урожая|Самосбор]]"
 
    else
    local latheId = frame.args[1] or ""
        return "[[Гидропоника#Тип урожая|Однолетнее]]"
     if latheId == "" then
         return '<div style="color:red;">Не указан ID станка.</div>'
     end
     end
end


     local lathe = nil
local function formatChemicals(seed)
     for _, data in ipairs(latheData or {}) 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
    -- Построение словаря материалов по их ID
        local target = findSeedById(mu, data)
     local materialMapping = {}
         if target and target.productPrototypes then
     for _, material in ipairs(materialData or {}) do
             for _, prod in ipairs(target.productPrototypes) do
         if material.id then
                table.insert(list, ("<li>{{Предмет|%s|link=Гидропоника#{{#invoke:Entity Lookup|getname|%s}}}}</li>"):format(prod, prod))
             -- Приоритет: stackEntity > id > name
             end
             materialMapping[ material.id ] = material.stackEntity or material.id or material.name
         end
         end
     end
     end
    return "<ul>" .. table.concat(list) .. "</ul>"
end


    local chemMapping = {}
local function generateHeader()
     for id, chem in pairs(chemData or {}) 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 = cssLink
local function generateFooter()
    local recipes = {}
    return "|}"
 
end
    local function getRecipeDetails(recipeId)
        for _, recipe in ipairs(recipeData or {}) do
            if recipe.id == recipeId then
                return recipe
            end
        end
        return nil
    end


    local function findInResearch(recipeId)
function p.table(frame)
        for _, research in ipairs(researchData or {}) do
    local data = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data")
            if research.technology and research.technology.recipeUnlocks then
    local rows = {}
                for _, unlock in ipairs(research.technology.recipeUnlocks) do
                    if unlock == recipeId then
                        return {
                            name = research.technology.name,
                            tier = research.technology.tier,
                            discipline = research.technology.discipline
                        }
                    end
                end
            end
        end
        return nil
    end


     -- Обработка staticRecipes
     for _, seed in ipairs(data) do
    if lathe.Lathe and lathe.Lathe.staticRecipes then
        local prodId = seed.productPrototypes[1]
        for _, recipeId in ipairs(lathe.Lathe.staticRecipes) do
        local seedId = seed.packetPrototype
            local recipe = getRecipeDetails(recipeId)
        local seedName = string.format('{{#invoke:Entity Lookup|getname|%s}}', seedId)
            if recipe and recipe.result then
                table.insert(recipes, {
                    result = recipe.result,
                    completetime = recipe.completetime,
                    materials = recipe.materials,
                    discipline = "Static",
                    tier = 0
                })
            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 anchor  = string.format('{{anchor|%s}}', seedName)
    if lathe.Lathe and lathe.Lathe.dynamicRecipes then
        local fruitImg = string.format(
         for _, recipeId in ipairs(lathe.Lathe.dynamicRecipes) do
            '{{Предмет|%s|size=64px|vertical=1|imageTooltip=1|link=%s}}',
            local recipe = getRecipeDetails(recipeId)
            prodId, seedName
            if recipe then
        )
                local researchInfo = findInResearch(recipeId)
        local seedImg  = string.format(
                if researchInfo then
            '{{Предмет|%s|size=64px|vertical=1|imageTooltip=1|l=|link=%s}}',
                    table.insert(recipes, {
            seedId, seedName
                        result = recipe.result,
        )
                        completetime = recipe.completetime,
        local plantImg = string.format(
                        materials = recipe.materials,
            '{{Предмет|%s-harvest|size=64px|l=|link=%s}}',
                        discipline = researchInfo.discipline,
             seedId, seedName
                        tier = researchInfo.tier,
         )
                        researchName = researchInfo.name
                    })
                end
             end
         end
    end


     -- Обработка emagStaticRecipes
        local colGrowth     = formatCharacteristics(seed)
    if lathe.EmagLatheRecipes and lathe.EmagLatheRecipes.emagStaticRecipes then
         local colConditions = formatConditions(seed)
         for _, recipeId in ipairs(lathe.EmagLatheRecipes.emagStaticRecipes) do
        local colHarvest    = formatHarvestType(seed)
            local recipe = getRecipeDetails(recipeId)
        local colChemicals  = formatChemicals(seed)
            if recipe then
        local colMutations  = formatMutations(seed, data)
                table.insert(recipes, {
                    result = recipe.result,
                    completetime = recipe.completetime,
                    materials = recipe.materials,
                    discipline = "Static",
                    tier = 0,
                    isEmag = true
                })
            end
        end
    end


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


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


    -- Таблица для перевода названий дисциплин
function p.main(frame)
     local disciplineMapping = {
     local args = frame.args
        Arsenal          = "Арсенал",
    local id = args[1]
        Industrial        = "Промышленность",
    local mode  = mw.text.trim(args[2] or ""):lower()
        Experimental      = "Экспериментальное",
    local seed = findSeedById(id, seedsData)
        CivilianServices  = "Обслуживание персонала"
    if not seed then return "" end
    }


     -- Таблица для цветов по уровням
     if mode  == "growth" then
    local tierColors = {
         return formatCharacteristics(seed)
        [1] = "#54d554",
     elseif mode  == "conditions" then
         [2] = "#ed9000",
         return formatConditions(seed)
        [3] = "#d72a2a"
    elseif mode  == "harvest" then
    }
        return formatHarvestType(seed)
 
    elseif mode  == "chemicals" then
    local materialUseMultiplier = (lathe.Lathe and lathe.Lathe.materialUseMultiplier) or 1
        return formatChemicals(seed)
     local timeMultiplier        = (lathe.Lathe and lathe.Lathe.timeMultiplier) or 1
    elseif mode  == "mutations" then
 
         return formatMutations(seed, seedsData)
    for _, recipe in ipairs(recipes) do
    else
        local scaledTime = format_seconds_to_short_string(recipe.completetime * timeMultiplier)
         return ""
        out = out .. '{{Шаблон:Prototypes/Машина/Станок|product=' .. recipe.result
        out = out .. '|complete-time=' .. scaledTime
        out = out .. '|materials='
 
        local materials_str = ""
         if recipe.materials and 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
                materials_str = materials_str .. '<b>[[File:' .. stackEntity .. '.png|32x32px|link=]] '
                              .. scaledAmount .. ' {{#invoke:Entity Lookup|getname|' .. stackEntity .. '}}</b> '
            end
        else
            materials_str = 'Нет данных о материалах'
        end
 
        out = out .. materials_str
 
        -- Информация об исследовании
        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 .. ']], уровень: <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