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

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


-----------------------------
-- Загрузка данных
-- Функция для «очистки» JSON
local chemData = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data")
-----------------------------
local seedsData = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data")
local function cleanJSON(json)
 
    -- Удаляем запятую перед закрывающей квадратной скобкой (конец массива)
local function kelvinToCelsius(k)
    json = json:gsub(",%s*%]", "]")
     return k - 273.15
    -- Удаляем запятую перед закрывающей фигурной скобкой (конец объекта)
    json = json:gsub(",%s*%}", "}")
     return json
end
end


---------------------------------------------
local function findSeedById(id, data)
-- Функция для загрузки и парсинга JSON-файла
     for _, seed in ipairs(data) do
---------------------------------------------
        if seed.id == id then
local function loadJSONData(pageName)
            return seed
     local title = mw.title.new(pageName)
         end
    if not title then
        return {}
    end
    local jsonData = title:getContent() or ""
    jsonData = cleanJSON(jsonData)
    local success, data = pcall(mw.text.jsonDecode, jsonData)
    if success and type(data) == "table" then  
        return data
    else
         return {}
     end
     end
    return nil
end
end


-----------------------------------------------------------
local function formatCharacteristics(seed)
-- Загрузка данных: заменяем mw.loadData на loadJSONData()
    local parts = {
-----------------------------------------------------------
        ("[[Гидропоника#Потенция|Потенция]]: %s"):format(seed.potency or 1),
local latheData    = loadJSONData("User:IanComradeBot/prototypes/lathe.json")
        ("[[Гидропоника#Урожайность|Урожайность]]: %s"):format(seed.yield),
local recipeData  = loadJSONData("User:IanComradeBot/prototypes/lathe/recipes.json")
        ("[[Гидропоника#Срок жизни|Срок жизни]]: %s"):format(seed.lifespan),
local researchData = loadJSONData("User:IanComradeBot/prototypes/research.json")
        ("[[Гидропоника#Созревание|Созревание]]: %s"):format(seed.maturation),
local materialData = loadJSONData("User:IanComradeBot/prototypes/materials.json")
        ("[[Гидропоника#Производство|Производство]]: %s"):format(seed.production),
local chemData    = loadJSONData("User:IanComradeBot/chem prototypes.json")
        ("[[Гидропоника#Стадии роста|Стадии роста]]: %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),
local function format_seconds_to_short_string(input_seconds)
        ("[[Гидропоника#Потребление нутриентов|Удобрение]]: %s"):format(seed.nutrientConsumption or 0.75),
     local minutes = math.floor(input_seconds / 60)
        ("[[Гидропоника#Оптимальная температура|Темп.]]: %.2f°C"):format(kelvinToCelsius(seed.idealHeat or 293)),
     local seconds = input_seconds % 60
    }
     return table.concat(parts, '<br>')
end


     local minutes_part = minutes > 0 and (minutes .. " мин.") or nil
local function formatHarvestType(seed)
     local seconds_part = seconds > 0 and (seconds .. " сек.") or nil
     return seed.harvestRepeat and "[[Гидропоника#Тип урожая|" .. tostring(seed.harvestRepeat) .. "]]" or "-"
 
end
     if minutes_part and seconds_part then
local function formatHarvestType(seed)
         return minutes_part .. " " .. seconds_part
     local harvestRepeat = seed.harvestRepeat
     elseif seconds_part then
     if harvestRepeat == "Repeat" then
         return seconds_part
         return "[[Гидропоника#Тип урожая|Многолетнее]]"
    elseif minutes_part then
     elseif harvestRepeat == "SelfHarvest" then
        return minutes_part
         return "[[Гидропоника#Тип урожая|Самосбор]]"
     else
     else
         return '0 сек.'
         return "[[Гидропоника#Тип урожая|Однолетнее]]"
     end
     end
end
end


-----------------------------------------------------------
local function formatChemicals(seed)
-- Функция для сортировки рецептов
     if not seed.chemicals then return "-" end
-----------------------------------------------------------
    local list = {}
local function sortRecipesByPriority(recipes)
    for chemId, vals in pairs(seed.chemicals) do
     table.sort(recipes, function(a, b)
         local entry = chemData[chemId]
        local priority = { Static = 1, EMAG = 3 }
         local chemName = entry and entry.name or chemId
         local aPriority = priority[a.discipline] or 2
         table.insert(list, string.format(
         local bPriority = priority[b.discipline] or 2
            "<li>[[Химия#chem_%s|%s]] (мин: %s, макс: %s, дел: %s)</li>",
 
             chemId, chemName, vals.Min or 0, vals.Max or 0, vals.PotencyDivisor or 1
         if a.isEmag ~= b.isEmag then
        ))
             return not a.isEmag
    end
        end
    return "<ul>" .. table.concat(list) .. "</ul>"
end


        if aPriority == bPriority then
local function formatMutations(seed, data)
             if a.tier == b.tier then
    if not seed.mutationPrototypes then return "-" end
                 return a.discipline < b.discipline
    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
            return a.tier < b.tier
         end
         end
    end
    return "<ul>" .. table.concat(list) .. "</ul>"
end


        return aPriority < bPriority
local function generateHeader()
    end)
    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
end


-----------------------------------------------------------
local function generateFooter()
-- Основная функция модуля
     return "|}"
-----------------------------------------------------------
end
function p.main(frame)
     -- Подключение CSS
    local cssLink = frame:extensionTag('templatestyles', '', {
        src = 'Шаблон:Prototypes/Машина/Станок/styles.css'
    })


     local latheId = frame.args[1] or ""
function p.table(frame)
    if latheId == "" then
     local data = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data")
        return '<div style="color:red;">Не указан ID станка.</div>'
     local rows = {}
     end


    local lathe = nil
     for _, seed in ipairs(data) do
     for _, data in ipairs(latheData) do
         local prodId = seed.productPrototypes[1]
         if data.id == latheId then
        local seedId = seed.packetPrototype
            lathe = data
         local seedName = string.format('{{#invoke:Entity Lookup|getname|%s}}', seedId)
            break
         end
    end


    if not lathe then
        local anchor  = string.format('{{anchor|%s}}', seedName)
         return '<div style="color:red;">Станок с ID "' .. latheId .. '" не найден.</div>'
         local fruitImg = string.format(
    end
            '{{Предмет|%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 materialMapping = {}
        local colGrowth     = formatCharacteristics(seed)
    for _, material in ipairs(materialData) do
        local colConditions = formatConditions(seed)
         if material.id then
        local colHarvest    = formatHarvestType(seed)
            materialMapping[material.id] = material.stackEntity or material.id or material.name
         local colChemicals  = formatChemicals(seed)
         end
         local colMutations  = formatMutations(seed, data)
    end


    local chemMapping = {}
        local row = frame:preprocess(string.format(
    for id, chem in pairs(chemData) do
            [[|-
         chemMapping[id] = chem.name
            ! %s
            ! %s
            ! %s
            | %s
            | %s
            | %s
            | %s
            | %s ]],
            fruitImg, seedImg, plantImg,
            colGrowth, colConditions, colHarvest,
            colChemicals, colMutations
        ))
         table.insert(rows, row)
     end
     end


     local out = cssLink
     return generateHeader() .. table.concat(rows, '\n') .. '\n' .. generateFooter()
    local recipes = {}
end


     local function getRecipeDetails(recipeId)
function p.main(frame)
        for _, recipe in ipairs(recipeData) do
    local args = frame.args
            if recipe.id == recipeId then
    local id = args[1]
                return recipe
     local mode  = mw.text.trim(args[2] or ""):lower()
            end
    local seed = findSeedById(id, seedsData)
        end
    if not seed then return "" end
        return nil
    end


     local function findInResearch(recipeId)
     if mode  == "growth" then
        for _, research in ipairs(researchData) do
         return formatCharacteristics(seed)
            if research.technology and research.technology.recipeUnlocks then
    elseif mode == "conditions" then
                for _, unlock in ipairs(research.technology.recipeUnlocks) do
         return formatConditions(seed)
                    if unlock == recipeId then
     elseif mode  == "harvest" then
                        return {
         return formatHarvestType(seed)
                            name = research.technology.name,
     elseif mode  == "chemicals" then
                            tier = research.technology.tier,
         return formatChemicals(seed)
                            discipline = research.technology.discipline
     elseif mode  == "mutations" then
                        }
        return formatMutations(seed, seedsData)
                    end
    else
                end
         return ""
            end
        end
         return nil
    end
 
    -- Обработка staticRecipes
    if lathe.Lathe and lathe.Lathe.staticRecipes then
        for _, recipeId in ipairs(lathe.Lathe.staticRecipes) do
            local recipe = getRecipeDetails(recipeId)
            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
    if lathe.Lathe and lathe.Lathe.dynamicRecipes then
         for _, recipeId in ipairs(lathe.Lathe.dynamicRecipes) 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
                    })
                end
            end
        end
     end
 
    -- Обработка emagStaticRecipes
    if lathe.EmagLatheRecipes and lathe.EmagLatheRecipes.emagStaticRecipes then
        for _, recipeId in ipairs(lathe.EmagLatheRecipes.emagStaticRecipes) do
            local recipe = getRecipeDetails(recipeId)
            if recipe then
                table.insert(recipes, {
                    result = recipe.result,
                    completetime = recipe.completetime,
                    materials = recipe.materials,
                    discipline = "Static",
                    tier = 0,
                    isEmag = true
                })
            end
        end
    end
 
    -- Обработка emagDynamicRecipes
    if lathe.EmagLatheRecipes and lathe.EmagLatheRecipes.emagDynamicRecipes then
         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)
 
    -- Таблица для перевода названий дисциплин
    local disciplineMapping = {
        Arsenal = "Арсенал",
         Industrial = "Промышленность",
        Experimental = "Экспериментальное",
        CivilianServices = "Обслуживание персонала"
    }
 
    -- Таблица для цветов по уровням
    local tierColors = {
        [1] = "#54d554",
        [2] = "#ed9000",
        [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