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

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


-- Функция для загрузки данных плат из JSON-файла
-- Загрузка данных
local function loadData()
local chemData = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data")
return mw.text.jsonDecode(mw.title.new("User:IanComradeBot/armor_prototypes.json"):getContent())
local seedsData = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data")
 
local function kelvinToCelsius(k)
    return k - 273.15
end
end


-- Функция для поиска данных по ID
local function findSeedById(id, data)
local function findDataById(dataCache, id)
    for _, seed in ipairs(data) do
for _, item in ipairs(dataCache) do
        if seed.id == id then
if item.id == id then
            return seed
return item
        end
end
    end
end
    return nil
return nil
end
end


-- Функция для точного округления до ближайшего целого числа
local function formatCharacteristics(seed)
local function round(num)
    local parts = {
return math.floor(num + 0.5)
        ("[[Гидропоника#Потенция|Потенция]]: %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 formatPercentage(value)
    local parts = {
return value and round((1 - value) * 100) .. "%" or "-"
        ("[[Гидропоника#Потребление воды|Вода]]: %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
end


-- Функция для создания строк для таблицы по типу защиты
local function formatHarvestType(seed)
local function createProtectionRow(class, color, value)
    return seed.harvestRepeat and "[[Гидропоника#Тип урожая|" .. tostring(seed.harvestRepeat) .. "]]" or "-"
return '|class="' .. class .. '" style="font-weight:bold;color: ' .. color .. ';"|' .. value .. '\n'
end
local function formatHarvestType(seed)
    local harvestRepeat = seed.harvestRepeat
    if harvestRepeat == "Repeat" then
        return "[[Гидропоника#Тип урожая|Многолетнее]]"
    elseif harvestRepeat == "SelfHarvest" then
        return "[[Гидропоника#Тип урожая|Самосбор]]"
    else
        return "[[Гидропоника#Тип урожая|Однолетнее]]"
    end
end
end


function p.main(frame)
local function formatChemicals(seed)
local dataCache = loadData()
    if not seed.chemicals then return "-" end
local id = frame.args.id or "" -- ID предмета
    local list = {}
local itemData = findDataById(dataCache, id)
    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


-- Получаем защитные значения из coefficients, если они присутствуют
local function formatMutations(seed, data)
local coefficients = itemData and itemData.coefficients
    if not seed.mutationPrototypes then return "-" end
local protBlunt = formatPercentage(coefficients and coefficients.Blunt)
    local list = {}
local protSlash = formatPercentage(coefficients and coefficients.Slash)
    for _, mu in ipairs(seed.mutationPrototypes) do
local protPiercing = formatPercentage(coefficients and coefficients.Piercing)
        local target = findSeedById(mu, data)
local protHeat = formatPercentage(coefficients and coefficients.Heat)
        if target and target.productPrototypes then
local protRadiation = formatPercentage(coefficients and coefficients.Radiation)
            for _, prod in ipairs(target.productPrototypes) do
local protCaustic = formatPercentage(coefficients and coefficients.Caustic)
                table.insert(list, ("<li>{{Предмет|%s|link=Гидропоника#{{#invoke:Entity Lookup|getname|%s}}}}</li>"):format(prod, prod))
            end
local protExplosion = itemData and itemData.ExplosionResistance and itemData.ExplosionResistance.damageCoefficient
        end
    end
    return "<ul>" .. table.concat(list) .. "</ul>"
end


-- Получаем значения sprintModifier, walkModifier, fireProtection, и temperatureProtection
local function generateHeader()
local sprintModifier = itemData and itemData.sprintModifier
    return [[
local walkModifier = itemData and itemData.walkModifier
{| id="BOTANY" class="wikitable sortable mw-collapsible" style="width:100%;"
local fireProtection = itemData and itemData.FireProtection and itemData.FireProtection.reduction
! rowspan="2" style="width:10%;" | Плод
local temperatureProtection = itemData and itemData.TemperatureProtection
! rowspan="2" class="unsortable" style="width:5%;" | Семена
local speedDescription = ""
! 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


-- Формируем сообщение в зависимости от значений sprintModifier и walkModifier
local function generateFooter()
if sprintModifier and walkModifier then
    return "|}"
local sprintPercent = round((1 - sprintModifier) * 100)
end
local walkPercent = round((1 - walkModifier) * 100)


speedDescription = "* Понижает скорость " .. (sprintModifier == walkModifier and "передвижения" or "бега и ходьбы") ..
function p.table(frame)
  " на <span style=\"color:yellow\">'''" .. sprintPercent .. " %'''</span>\n"
    local data = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data")
if sprintModifier ~= walkModifier then
    local rows = {}
speedDescription = speedDescription .. "* Понижает скорость ходьбы на <span style=\"color:yellow\">'''" .. walkPercent .. " %'''</span>\n"
end
end


-- Формируем сообщение для огневой защиты, если значение присутствует
    for _, seed in ipairs(data) do
local fireProtectionDescription = fireProtection and
        local prodId = seed.productPrototypes[1]
"* Имеет огневую защиту в <span style=\"color:OrangeRed\">'''" .. round((1 - fireProtection) * 100) .. " %'''</span>\n" or ""
        local seedId = seed.packetPrototype
        local seedName = string.format('{{#invoke:Entity Lookup|getname|%s}}', seedId)


-- Формируем сообщение для сопротивления к критическим температурам, если значение присутствует
        local anchor  = string.format('{{anchor|%s}}', seedName)
local temperatureProtectionDescription = temperatureProtection and
        local fruitImg = string.format(
"* Имеет значительное сопротивление к критическим температурам\n" or ""
            '{{Предмет|%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 description = (frame.args.description or "") .. '\n' .. speedDescription .. fireProtectionDescription .. temperatureProtectionDescription -- Описание
        local colConditions = formatConditions(seed)
local location = frame.args.location or "" -- Местонахождение
        local colHarvest    = formatHarvestType(seed)
local created = frame.args.created or "" -- Создание
        local colChemicals  = formatChemicals(seed)
        local colMutations  = formatMutations(seed, data)


local anchorName = frame.args.anchorName or "" -- Название якоря
        local row = frame:preprocess(string.format(
local backgroundColor = frame.args.backgroundColor or "" -- Цвет фона первой ячейки
            [[|-
local class = frame.args.class or "" -- Класс
            ! %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()
local out = ''
end
out = out .. '!class="' .. class .. '" style="background-color: ' .. backgroundColor .. ';"|' .. frame:preprocess('{{Anchor|' .. anchorName .. '}}')
out = out .. frame:preprocess('{{#invoke:Entity Lookup|createimagetooltip|File:' .. id .. '.png|' .. id .. '|Мета=64x64px,link=}}')
out = out .. '<br>' .. frame:preprocess('{{#invoke:Entity Lookup|getname|' .. id .. '}}') .. '\n'


-- Используем функцию для формирования строк защиты
function p.main(frame)
out = out .. createProtectionRow(class, "crimson", protBlunt)
    local args = frame.args
out = out .. createProtectionRow(class, "indianred", protSlash)
    local id = args[1]
out = out .. createProtectionRow(class, "darksalmon", protPiercing)
    local mode  = mw.text.trim(args[2] or ""):lower()
out = out .. createProtectionRow(class, "orange", protHeat)
    local seed = findSeedById(id, seedsData)
out = out .. createProtectionRow(class, "plum", protCaustic)
    if not seed then return "" end
out = out .. createProtectionRow(class, "limegreen", protRadiation)
out = out .. createProtectionRow(class, "tan", protExplosion)
 
out = out .. '|class="' .. class .. '" style=""|\n' .. description .. '\n'
out = out .. '|class="' .. class .. '" style=""|\n'
 
 
-- Проверка класса на "spacesuit-helmet"
if class == "spacesuit-helmet" then
out = out .. frame:preprocess("{{FrameText|color = #bcceff|border-color = #4c4c61|content = Находится в скафандре}}")
-- Местоположение
elseif location ~= "" then
out = out .. frame:preprocess('{{SlideMenu|overlay|color=#e1f6ff|title=Список [[File:Examine.svg.192dpi.png|24x24px]]|content=<p></p>\n' .. location .. '}}\n')
end
 
-- Создаётся
if created ~= "" then
out = out .. frame:preprocess('{{SlideMenu|overlay|color=#e1f6ff|border-color=#4c4c61|title=Создаётся [[File:hammer.svg.192dpi.png|24x24px]]|content=Создаётся в панели строительства<hr>\n' .. created .. '}}\n')
elseif location == "" and class ~= "spacesuit-helmet" then
out = out .. frame:preprocess('{{FrameText|color=#82d1c4|content=Нет гарантированных мест спавна}}\n')
end
 
out = out .. '|-\n'


return out
    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
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