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

Нет описания правки
мНет описания правки
 
(не показано 340 промежуточных версий этого же участника)
Строка 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/Песочница.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 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


function p.main(frame)
local function formatHarvestType(seed)
     -- Подключение CSS
    return seed.harvestRepeat and "[[Гидропоника#Тип урожая|" .. tostring(seed.harvestRepeat) .. "]]" or "-"
     local cssLink = frame:extensionTag('templatestyles', '', {
end
         src = 'Шаблон:Research/styles.css'
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 dataCache = loadResearchData()
local function generateHeader()
     local discipline = frame.args[1] or ""
     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


     if discipline and discipline ~= "" then
local function generateFooter()
        -- Инициализация строки вывода
     return "|}"
        local out = cssLink .. '<div class="research-group">'
end


        -- Получаем список исследований по дисциплине
function p.table(frame)
        local researches = findResearchByDiscipline(dataCache, discipline)
    local data = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data")
    local rows = {}


         if #researches == 0 then
    for _, seed in ipairs(data) do
            out = out .. '<div style="color:red;">Нет исследований для дисциплины "' .. discipline .. '"</div>'
         local prodId = seed.productPrototypes[1]
        end
        local seedId = seed.packetPrototype
        local seedName = string.format('{{#invoke:Entity Lookup|getname|%s}}', seedId)


         for _, tech in ipairs(researches) do
         local anchor  = string.format('{{anchor|%s}}', seedName)
            local disciplineName = disciplineMapping[tech.discipline] or "Неизвестная дисциплина"
        local fruitImg = string.format(
             local tierColor = tierColors[tech.tier] or "#FFFFFF"
             '{{Предмет|%s|size=64px|vertical=1|imageTooltip=1|link=%s}}',
             local iconPath = tech.icon and tech.icon.sprite or nil
            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
        )


            -- Формирование строки prerequisites
        local colGrowth    = formatCharacteristics(seed)
            local prerequisitesStr = ""
        local colConditions = formatConditions(seed)
            if tech.technologyPrerequisites and #tech.technologyPrerequisites > 0 then
        local colHarvest    = formatHarvestType(seed)
                prerequisitesStr = '<ul>'
        local colChemicals  = formatChemicals(seed)
                for _, prerequisite in ipairs(tech.technologyPrerequisites) do
        local colMutations  = formatMutations(seed, data)
                    if prerequisite and prerequisite ~= "" then
                        prerequisitesStr = prerequisitesStr .. '<li>{{#invoke:Entity Lookup|createimagetooltip|Файл:'
                            .. prerequisite .. '.png|' .. prerequisite
                            .. '|Мета=32x32px,link=}}'
                            .. prerequisite .. '</li>'
                    end
                end
                prerequisitesStr = prerequisitesStr .. '</ul>'
            end


             -- Формирование строки unlocks
        local row = frame:preprocess(string.format(
             local unlocksStr = ""
             [[|-
             if tech.recipeUnlocks and #tech.recipeUnlocks > 0 then
             ! %s
                unlocksStr = '<ul>'
             ! %s
                for _, recipe in ipairs(tech.recipeUnlocks) do
            ! %s
                    if recipe and recipe ~= "" then
            | %s
                        unlocksStr = unlocksStr .. '<li>{{#invoke:Entity Lookup|createimagetooltip|Файл:'
            | %s
                            .. recipe .. '.png|' .. recipe
            | %s
                            .. '|Мета=32x32px,link=}} {{#invoke:Entity Lookup|getname|'
            | %s
                            .. recipe .. '}}</li>'
            | %s ]],
                    end
            fruitImg, seedImg, plantImg,
                end
            colGrowth, colConditions, colHarvest,
                unlocksStr = unlocksStr .. '</ul>'
            colChemicals, colMutations
            end
        ))
         end
         table.insert(rows, row)
     end
     end


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


return p
return p