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

Материал из Space Station 14 Вики
Нет описания правки
мНет описания правки
 
(не показано 357 промежуточных версий этого же участника)
Строка 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 then
 
return nil
local function kelvinToCelsius(k)
end
    return k - 273.15
return mw.text.jsonDecode(content)
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
end


-- Функция для поиска исследований по дисциплине
local function formatConditions(seed)
local function findResearchByDiscipline(dataCache, discipline)
    local parts = {
local results = {}
        ("[[Гидропоника#Потребление воды|Вода]]: %s"):format(seed.waterConsumption or 0.5),
for _, research in ipairs(dataCache) do
        ("[[Гидропоника#Потребление нутриентов|Удобрение]]: %s"):format(seed.nutrientConsumption or 0.75),
if research.technology and research.technology.discipline == discipline then
        ("[[Гидропоника#Оптимальная температура|Темп.]]: %.2f°C"):format(kelvinToCelsius(seed.idealHeat or 293)),
table.insert(results, research.technology)
    }
end
    return table.concat(parts, '<br>')
end
return results
end
end


-- Таблица для перевода названий дисциплин
local function formatHarvestType(seed)
local disciplineMapping = {
    return seed.harvestRepeat and "[[Гидропоника#Тип урожая|" .. tostring(seed.harvestRepeat) .. "]]" or "-"
Arsenal = "Арсенал",
end
Industrial = "Промышленность",
local function formatHarvestType(seed)
Experimental = "Экспериментальное",
    local harvestRepeat = seed.harvestRepeat
CivilianServices = "Обслуживание персонала"
    if harvestRepeat == "Repeat" then
}
        return "[[Гидропоника#Тип урожая|Многолетнее]]"
    elseif harvestRepeat == "SelfHarvest" then
        return "[[Гидропоника#Тип урожая|Самосбор]]"
    else
        return "[[Гидропоника#Тип урожая|Однолетнее]]"
    end
end


-- Таблица для цветов по уровням
local function formatChemicals(seed)
local tierColors = {
    if not seed.chemicals then return "-" end
[1] = "#54d554",
    local list = {}
[2] = "#ed9000",
    for chemId, vals in pairs(seed.chemicals) do
[3] = "#d72a2a"
        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


function p.main(frame)
local function formatMutations(seed, data)
-- Подключение CSS
    if not seed.mutationPrototypes then return "-" end
local cssLink = frame:extensionTag('templatestyles', '', {
    local list = {}
src = 'Шаблон:Research/styles.css'
    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()
local dataCache = loadResearchData()
    return [[
if not dataCache then
{| id="BOTANY" class="wikitable sortable mw-collapsible" style="width:100%;"
return cssLink .. '<div style="color:red;">Ошибка загрузки данных исследований. Проверьте файл JSON.</div>'
! rowspan="2" style="width:10%;" | Плод
end
! 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()
local discipline = frame.args[1] or ""
    return "|}"
if discipline == "" then
end
return cssLink .. '<div style="color:red;">Не указана дисциплина. Доступные дисциплины: '
.. table.concat(vim.tbl_keys(disciplineMapping), ", ") .. '</div>'
end


-- Инициализация строки вывода
function p.table(frame)
local out = cssLink .. '<div class="research-group">'
    local data = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data")
    local rows = {}


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


-- Формирование блоков исследований
        local anchor  = string.format('{{anchor|%s}}', seedName)
for _, tech in ipairs(researches) do
        local fruitImg = string.format(
local disciplineName = disciplineMapping[tech.discipline] or "Неизвестная дисциплина"
            '{{Предмет|%s|size=64px|vertical=1|imageTooltip=1|link=%s}}',
local tierColor = tierColors[tech.tier] or "#FFFFFF"
            prodId, seedName
local iconPath = tech.icon and tech.icon.sprite or nil
        )
        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)
if not tech.id or not tech.name then
        local colConditions = formatConditions(seed)
return cssLink .. '<div style="color:red;">Ошибка: отсутствует ID или имя технологии.</div>'
        local colHarvest    = formatHarvestType(seed)
end
        local colChemicals  = formatChemicals(seed)
        local colMutations  = formatMutations(seed, data)


-- Основной блок исследования
        local row = frame:preprocess(string.format(
out = out .. '<div class="research" id="' .. tech.id .. '">'
            [[|-
out = out .. frame:preprocess('<div class="research__images">[[Файл:{{#invoke:Entity Sprite|main|path|' .. (iconPath or "default_icon.png") .. '}}]]</div>')
            ! %s
out = out .. frame:preprocess('<div class="research__name">{{#invoke:Ftl|main|translation|' .. tech.name .. '}}[[Файл:' .. tech.discipline .. '.png|16px|link=]]</div>')
            ! %s
out = out .. '<div class="research__type">'
            ! %s
out = out .. '<div>Уровень: <span style="color:' .. tierColor .. ';">' .. (tech.tier or "N/A") .. '</span></div>'
            | %s
out = out .. '<div class="research__technology">' .. disciplineName .. '</div>'
            | %s
out = out .. '<div>Стоимость: <span style="color:#DA70D6;">' .. (tech.cost or "N/A") .. '</span></div>'
            | %s
out = out .. '</div>'
            | %s
            | %s ]],
            fruitImg, seedImg, plantImg,
            colGrowth, colConditions, colHarvest,
            colChemicals, colMutations
        ))
        table.insert(rows, row)
    end


-- Блок необходимых исследований
    return generateHeader() .. table.concat(rows, '\n') .. '\n' .. generateFooter()
if tech.recipeUnlocks and #tech.recipeUnlocks > 0 then
end
    out = out .. '<div class="research__technologies-unlocks">Разблокирует:'
 
    out = out .. '<ul>'
function p.main(frame)
    local args = frame.args
    for _, recipe in ipairs(tech.recipeUnlocks) do
    local id = args[1]
        -- Проверяем, что recipe не пустой и валидный
    local mode  = mw.text.trim(args[2] or ""):lower()
        if recipe and recipe ~= "" then
    local seed = findSeedById(id, seedsData)
            out = out .. frame:preprocess('<li>{{#invoke:Entity Lookup|createimagetooltip|Файл:'
    if not seed then return "" end
                .. recipe .. '.png|' .. recipe
                .. '|Мета=32x32px,link=}} {{#invoke:Entity Lookup|getname|'
                .. recipe .. '}}</li>')
        else
            out = out .. '<li style="color:red;">Ошибка: некорректный рецепт.</li>'
        end
    end
    out = out .. '</ul>'
    out = out .. '</div>'
end
out = out .. '</div>'
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
        return ""
    end
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