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

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


-- Функция для загрузки данных исследований из JSON-файла
-- Загрузка данных
local function loadResearchData()
local chemData = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data")
    local content = mw.title.new("User:IanComradeBot/Песочница.json"):getContent()
local seedsData = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data")
    if not content or content == "" then
 
        error("JSON-файл пуст или отсутствует!")
local function kelvinToCelsius(k)
    end
     return k - 273.15
    local data = mw.text.jsonDecode(content)
    if not data then
        error("Ошибка парсинга JSON!")
    end
     return data
end
end


-- Функция для поиска исследований по дисциплине
local function findSeedById(id, data)
local function findResearchByDiscipline(dataCache, discipline)
     for _, seed in ipairs(data) do
    local results = {}
         if seed.id == id then
     for _, research in ipairs(dataCache) do
             return seed
         if research.technology and research.technology.discipline == discipline then
             table.insert(results, research.technology)
         end
         end
     end
     end
     return results
     return nil
end
end


-- Таблица для перевода названий дисциплин
local function formatCharacteristics(seed)
local disciplineMapping = {
    local parts = {
    Arsenal = "Арсенал",
        ("[[Гидропоника#Потенция|Потенция]]: %s"):format(seed.potency or 1),
    Industrial = "Промышленность",
        ("[[Гидропоника#Урожайность|Урожайность]]: %s"):format(seed.yield),
    Experimental = "Экспериментальное",
        ("[[Гидропоника#Срок жизни|Срок жизни]]: %s"):format(seed.lifespan),
    CivilianServices = "Обслуживание персонала"
        ("[[Гидропоника#Созревание|Созревание]]: %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 tierColors = {
    local parts = {
    [1] = "#54d554",
        ("[[Гидропоника#Потребление воды|Вода]]: %s"):format(seed.waterConsumption or 0.5),
    [2] = "#ed9000",
        ("[[Гидропоника#Потребление нутриентов|Удобрение]]: %s"):format(seed.nutrientConsumption or 0.75),
    [3] = "#d72a2a"
        ("[[Гидропоника#Оптимальная температура|Темп.]]: %.2f°C"):format(kelvinToCelsius(seed.idealHeat or 293)),
}
    }
    return table.concat(parts, '<br>')
end


-- Универсальная функция для генерации списков
local function formatHarvestType(seed)
local function generateTemplate(list, templateType)
    return seed.harvestRepeat and "[[Гидропоника#Тип урожая|" .. tostring(seed.harvestRepeat) .. "]]" or "-"
     if not list or #list == 0 then
end
         return ""
local function formatHarvestType(seed)
    local harvestRepeat = seed.harvestRepeat
     if harvestRepeat == "Repeat" then
        return "[[Гидропоника#Тип урожая|Многолетнее]]"
    elseif harvestRepeat == "SelfHarvest" then
         return "[[Гидропоника#Тип урожая|Самосбор]]"
    else
        return "[[Гидропоника#Тип урожая|Однолетнее]]"
     end
     end
end


     local result = "<ul>"
local function formatChemicals(seed)
     for _, entry in ipairs(list) do
    if not seed.chemicals then return "-" end
         if entry and entry ~= "" then
     local list = {}
            if templateType == "prerequisite" then
     for chemId, vals in pairs(seed.chemicals) do
                result = result .. '<li>{{#invoke:Entity Lookup|createimagetooltip|Файл:'
         local entry = chemData[chemId]
                    .. entry .. '.png|' .. entry
        local chemName = entry and entry.name or chemId
                    .. '|Мета=32x32px,link=}} '
        table.insert(list, string.format(
                    .. entry .. '</li>'
            "<li>[[Химия#chem_%s|%s]] (мин: %s, макс: %s, дел: %s)</li>",
             elseif templateType == "unlock" then
            chemId, chemName, vals.Min or 0, vals.Max or 0, vals.PotencyDivisor or 1
                 result = result .. '<li>{{#invoke:Entity Lookup|createimagetooltip|Файл:'
        ))
                    .. entry .. '.png|' .. entry
    end
                    .. '|Мета=32x32px,link=}} {{#invoke:Entity Lookup|getname|'
    return "<ul>" .. table.concat(list) .. "</ul>"
                    .. entry .. '}}</li>'
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
         end
     end
     end
     result = result .. "</ul>"
     return "<ul>" .. table.concat(list) .. "</ul>"
end


     return result
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
end


function p.main(frame)
local function generateFooter()
     -- Подключение CSS
     return "|}"
    local cssLink = frame:extensionTag('templatestyles', '', {
end
        src = 'Шаблон:Research/styles.css'
    })


     local dataCache = loadResearchData()
function p.table(frame)
     local discipline = frame.args[1] or ""
     local data = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data")
     local rows = {}


     if discipline and discipline ~= "" then
     for _, seed in ipairs(data) do
         local out = cssLink .. '<div class="research-group">'
        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 researches = findResearchByDiscipline(dataCache, discipline)
        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
        )


         if #researches == 0 then
         local colGrowth    = formatCharacteristics(seed)
            out = out .. '<div style="color:red;">Нет исследований для дисциплины "' .. discipline .. '"</div>'
        local colConditions = formatConditions(seed)
         end
        local colHarvest    = formatHarvestType(seed)
        local colChemicals  = formatChemicals(seed)
         local colMutations  = formatMutations(seed, data)


         for _, tech in ipairs(researches) do
         local row = frame:preprocess(string.format(
             local disciplineName = disciplineMapping[tech.discipline] or "Неизвестная дисциплина"
             [[|-
             local tierColor = tierColors[tech.tier] or "#FFFFFF"
            ! %s
             local iconPath = tech.icon and tech.icon.sprite or nil
            ! %s
            ! %s
            | %s
            | %s
            | %s
            | %s
            | %s ]],
             fruitImg, seedImg, plantImg,
            colGrowth, colConditions, colHarvest,
             colChemicals, colMutations
        ))
        table.insert(rows, row)
    end


            -- Генерация строк prerequisites и unlocks
    return generateHeader() .. table.concat(rows, '\n') .. '\n' .. generateFooter()
            local prerequisitesStr = generateTemplate(tech.technologyPrerequisites, "prerequisite")
end
            local unlocksStr = generateTemplate(tech.recipeUnlocks, "unlock")


            -- Формируем вывод с использованием шаблона
function p.main(frame)
            out = out .. mw.getCurrentFrame():preprocess(
    local args = frame.args
                '{{Prototypes/Механика/Исследование' ..
    local id = args[1]
                '|id=' .. tech.id ..
    local mode  = mw.text.trim(args[2] or ""):lower()
                '|icon=' .. iconPath ..
    local seed = findSeedById(id, seedsData)
                '|name=' .. tech.name ..
    if not seed then return "" end
                '|discipline=' .. tech.discipline ..
                '|tier=' .. tech.tier ..
                '|tierColor=' .. tierColor ..
                '|disciplineName=' .. disciplineName ..
                '|cost=' .. tech.cost ..
                '|prerequisites=' .. prerequisitesStr ..
                '|unlocks=' .. unlocksStr ..
                '}}'
            )
        end


         out = out .. '</div>'
    if mode  == "growth" then
         return out
        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
     else
         return cssLink .. '<div style="color:red;">Дисциплина "' .. discipline .. '" не найдена.</div>'
         return ""
     end
     end
end
end


return p
return p