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

Материал из Space Station 14 Вики
мНет описания правки
Метка: отменено
мНет описания правки
Метка: отменено
Строка 1: Строка 1:
local p = {}
local p = {}


-- Конфигурация
local plantData = mw.loadData("Модуль:IanComradeBot/prototypes/chem/plant.json/data")
local CHEM_DATA_PATH = "Модуль:IanComradeBot/prototypes/chem/plant.json/data"
local chemData = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data")


-- Шаблоны описания эффектов
local EFFECT_TEMPLATES = {
local EFFECT_TEMPLATES = {
     PlantAdjustNutrition = "Увеличивает [[#Потребление нутриентов|нутриенты]] на %s.",
     PlantAdjustPotency      = "Изменяет [[#Потенция|потенцию]] на %s.",
     PlantAdjustHealth = "Изменяет [[#Здоровье|здоровье]] на %s.",
     PlantAdjustHealth       = "Изменяет [[#Здоровье|здоровье]] на %s.",
     PlantAdjustMutationMod = "Изменяет '''модификатор мутации''' на %s.",
     PlantAdjustNutrition    = "Изменяет [[#Потребление нутриентов|нутриенты]] на %s.",
     PlantAdjustToxins = "Увеличивает [[#Устойчивость к токсинам|токсины]] на %s.",
    PlantAdjustWater        = "Изменяет [[#Потребление воды|воду]] на %s.",
     PlantAdjustPests = "Уменьшает [[#Защита от вредителей|вредителей]] на %s.",
     PlantAdjustToxins       = "Изменяет [[#Устойчивость к токсинам|токсины]] на %s.",
     PlantAdjustWeeds = "Уменьшает [[#Защита от сорняков|сорняки]] на %s.",
     PlantAdjustPests         = "Изменяет [[#Защита от вредителей|вредителей]] на %s.",
     PlantAdjustPotency = "Изменяет [[#Потенция|потенцию]] на %s.",
     PlantAdjustWeeds         = "Изменяет [[#Защита от сорняков|сорняки]] на %s.",
     PlantAffectGrowth = "Увеличивает [[#Возраст|возраст]] на %s.",
     PlantAdjustMutationMod  = "Изменяет '''модификатор мутации''' на %s.",
     PlantAdjustWater = "Изменяет [[#Потребление воды|воду]] на %s.",
     PlantAdjustMutationLevel = "Изменяет '''уровень мутации''' на %s.",
    PlantAdjustMutationLevel = "Увеличивает '''уровень мутации''' на %s.",
     PlantAffectGrowth        = "Изменяет [[#Возраст|возраст]] на %s.",
     -- Для более сложных эффектов лучше использовать параметр manual_effects
     -- более сложные эффекты, которые находятся в коде
     PlantRestoreSeeds = "Восстанавливает семена (делает растение не [[#Бесплодное|бесплодным]], если оно было таковым).",
     PlantRestoreSeeds = "Восстанавливает семена (делает растение не [[#Бесплодное|бесплодным]], если оно было таковым).",
    PlantDestroySeeds = "Уничтожает семена (делает растение [[#Бесплодное|бесплодным]]).",
PlantDestroySeeds = "Уничтожает семена (делает растение [[#Бесплодное|бесплодным]]).",
     PlantPhalanximine = "Делает растение жизнеспособным (если оно было нежизнеспособным).",
     PlantPhalanximine = "Делает растение жизнеспособным (если оно было нежизнеспособным).",
     PlantCryoxadone = "Уменьшает возраст растения.",
     PlantCryoxadone   = "Уменьшает возраст растения.",
     RobustHarvest = "Запускает специфический эффект 'Робаст харвест'.",
     RobustHarvest     = "Специфический эффект:<ul>" ..
     PlantDiethylamine = "Запускает специфический эффект 'Диэтиламин'."
        "<li>Если [[#Потенция|потенция]] растения меньше 50, она увеличивается на {{цвет|text|good|c='''3'''}} (до максимума 50).</li>" ..
        "<li>Если [[#Потенция|потенция]] превышает 30, растение становится [[#Бесплодное|бесплодным]].</li>" ..
        "<li>Если [[#Потенция|потенция]] достигла 50 и [[#Урожайность|урожайность]] больше 1, то с шансом '''10 %''' [[#Урожайность|урожайность]] уменьшается на {{цвет|text|bad|c='''1'''}}.</li>" ..
    "</ul>",
     PlantDiethylamine = "Специфический эффект:<ul>" ..
        "<li>С шансом '''10 %''' увеличивает [[#Срок жизни|срок жизни]] на {{цвет|text|good|c='''1'''}}.</li>" ..
        "<li>С шансом '''10 %''' увеличивает [[#Выносливость|выносливость]] на {{цвет|text|good|c='''1'''}}.</li>" ..
    "</ul>",
}
}


-- Вспомогательные функции
-- Вспомогательные функции
local function formatAmount(amount)
local function formatEffect(effect)
     local color = amount > 0 and "good" or "bad"
     local rawType = effect['!type']
     return string.format("{{цвет|text|%s|c='''%s'''}}", color, tostring(amount))
    if not rawType then return "<li>Ошибка: не найден тип эффекта.</li>" end
end
     local effectType = rawType:gsub("%s*%b{}", "")


local function formatEffect(effect)
    local effectType = effect.type:gsub("!type:", "")
     local template = EFFECT_TEMPLATES[effectType]
     local template = EFFECT_TEMPLATES[effectType]
    if not template then
        return "<li>Неизвестный эффект: " .. effectType .. "</li>"
    end
     local description
     local description
     if effect.amount then
     if template then
        local formatted_amount = formatAmount(effect.amount)
        if effect.amount then
        description = string.format(template, formatted_amount)
            local num = tonumber(effect.amount)
            local color = num and (num > 0 and "good" or "bad") or "text"
            local amt = num and tostring(num) or tostring(effect.amount)
            description = string.format(template, string.format("{{цвет|text|%s|c='''%s'''}}", color, amt))
        else
            description = template
        end
     else
     else
         description = string.format(template, "")
         description = string.format("<code>Неизвестный эффект: %s</code>", effectType)
     end
     end


     if effect.probability and effect.probability < 1 then
     if effect.probability and effect.probability < 1 then
         local chance = tostring(effect.probability * 100)
         local pct = tostring(effect.probability * 100)
         description = string.format("С шансом '''%s %%''' %s", chance, mw.ustring.lower(mw.ustring.sub(description, 1, 1)) .. mw.ustring.sub(description, 2))
         description = string.format("С шансом '''%s %%:''' %s", pct, description:sub(1,1):lower() .. description:sub(2))
     end
     end


Строка 54: Строка 61:
end
end


-- Основная функция
function p.reagentRow(frame)
function p.reagentRow(frame)
     local args = frame:getParent().args
     local args       = frame.args
     local reagentId = args.id
     local reagentId = args.id or ""
 
     if reagentId == "" then
     if not reagentId then
         return [[<tr><td colspan="2">'''Ошибка: не указан ID реагента.'''</td></tr>]]
         return "<tr><td colspan='2'>'''Ошибка в модуле ReagentEffects: не указан ID реагента.'''</td></tr>"
     end
     end


     local success, chemData = pcall(mw.loadData, CHEM_DATA_PATH)
     local reagentEntry
    if not success or not chemData then
    for _, r in ipairs(plantData) do
        return string.format("<tr><td colspan='2'>'''Ошибка: не удалось загрузить данные из %s.'''</td></tr>", CHEM_DATA_PATH)
        if r.id == reagentId then reagentEntry = r; break end
     end
     end


     local reagent = chemData[reagentId]
     local chemEntry
     if not reagent then
     for _, c in ipairs(chemData) do
         return string.format("<tr><td colspan='2'>'''Ошибка: реагент с ID '%s' не найден в базе данных.'''</td></tr>", reagentId)
         if c.id == reagentId then chemEntry = c; break end
     end
     end


     local reagentName = reagent.name or reagentId
local entry = chemData[reagentId]
     local reagentName = entry and entry.name or reagentId
     local reagentCell = string.format("! [[Химия#chem_%s|%s]]", reagentId, reagentName)
     local reagentCell = string.format("! [[Химия#chem_%s|%s]]", reagentId, reagentName)


     local effectsList = {}
     local fragments = {}
     if reagent.plantMetabolism then
 
         for _, effectData in ipairs(reagent.plantMetabolism) do
     if reagentEntry and type(reagentEntry.plantMetabolism) == 'table' then
             table.insert(effectsList, formatEffect(effectData))
         for _, eff in ipairs(reagentEntry.plantMetabolism) do
             table.insert(fragments, formatEffect(eff))
         end
         end
     end
     end


     local manualEffects = args.manual_effects
     -- Ручное описание при вызове параметром "manualEffects"
     if manualEffects and manualEffects ~= '' then
     if args.manualEffects and args.manualEffects ~= "" then
         for line in mw.text.gsplit(manualEffects, "\n") do
         table.insert(fragments, args.manualEffects)
            if line ~= '' then
    end
                table.insert(effectsList, line)
 
            end
    if reagentEntry and reagentEntry.chemicals then
        end
        table.insert(fragments, formatChemicals(reagentEntry))
     end
     end


     local effectsCell = "| " .. table.concat(effectsList, "\n")
     local allItems    = table.concat(fragments)
    local effectsCell = string.format("| <ul>%s</ul>", allItems)


     return "|-\n" .. reagentCell .. "\n" .. effectsCell
     return frame:preprocess(string.format("|-\n%s\n%s", reagentCell, effectsCell))
end
end


return p
return p

Версия от 17:28, 25 июля 2025

Для документации этого модуля может быть создана страница Модуль:Песочница/Pok/doc

local p = {}

local plantData = mw.loadData("Модуль:IanComradeBot/prototypes/chem/plant.json/data")
local chemData = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data")

-- Шаблоны описания эффектов
local EFFECT_TEMPLATES = {
    PlantAdjustPotency       = "Изменяет [[#Потенция|потенцию]] на %s.",
    PlantAdjustHealth        = "Изменяет [[#Здоровье|здоровье]] на %s.",
    PlantAdjustNutrition     = "Изменяет [[#Потребление нутриентов|нутриенты]] на %s.",
    PlantAdjustWater         = "Изменяет [[#Потребление воды|воду]] на %s.",
    PlantAdjustToxins        = "Изменяет [[#Устойчивость к токсинам|токсины]] на %s.",
    PlantAdjustPests         = "Изменяет [[#Защита от вредителей|вредителей]] на %s.",
    PlantAdjustWeeds         = "Изменяет [[#Защита от сорняков|сорняки]] на %s.",
    PlantAdjustMutationMod   = "Изменяет '''модификатор мутации''' на %s.",
    PlantAdjustMutationLevel = "Изменяет '''уровень мутации''' на %s.",
    PlantAffectGrowth        = "Изменяет [[#Возраст|возраст]] на %s.",
    -- более сложные эффекты, которые находятся в коде
    PlantRestoreSeeds = "Восстанавливает семена (делает растение не [[#Бесплодное|бесплодным]], если оно было таковым).",
	PlantDestroySeeds = "Уничтожает семена (делает растение [[#Бесплодное|бесплодным]]).",
    PlantPhalanximine = "Делает растение жизнеспособным (если оно было нежизнеспособным).",
    PlantCryoxadone   = "Уменьшает возраст растения.",
    RobustHarvest     = "Специфический эффект:<ul>" ..
        "<li>Если [[#Потенция|потенция]] растения меньше 50, она увеличивается на {{цвет|text|good|c='''3'''}} (до максимума 50).</li>" ..
        "<li>Если [[#Потенция|потенция]] превышает 30, растение становится [[#Бесплодное|бесплодным]].</li>" ..
        "<li>Если [[#Потенция|потенция]] достигла 50 и [[#Урожайность|урожайность]] больше 1, то с шансом '''10 %''' [[#Урожайность|урожайность]] уменьшается на {{цвет|text|bad|c='''1'''}}.</li>" ..
    "</ul>",
    PlantDiethylamine = "Специфический эффект:<ul>" ..
        "<li>С шансом '''10 %''' увеличивает [[#Срок жизни|срок жизни]] на {{цвет|text|good|c='''1'''}}.</li>" ..
        "<li>С шансом '''10 %''' увеличивает [[#Выносливость|выносливость]] на {{цвет|text|good|c='''1'''}}.</li>" ..
    "</ul>",
}

-- Вспомогательные функции
local function formatEffect(effect)
    local rawType = effect['!type']
    if not rawType then return "<li>Ошибка: не найден тип эффекта.</li>" end
    local effectType = rawType:gsub("%s*%b{}", "")

    local template = EFFECT_TEMPLATES[effectType]
    local description
    if template then
        if effect.amount then
            local num = tonumber(effect.amount)
            local color = num and (num > 0 and "good" or "bad") or "text"
            local amt = num and tostring(num) or tostring(effect.amount)
            description = string.format(template, string.format("{{цвет|text|%s|c='''%s'''}}", color, amt))
        else
            description = template
        end
    else
        description = string.format("<code>Неизвестный эффект: %s</code>", effectType)
    end

    if effect.probability and effect.probability < 1 then
        local pct = tostring(effect.probability * 100)
        description = string.format("С шансом '''%s %%:''' %s", pct, description:sub(1,1):lower() .. description:sub(2))
    end

    return "<li>" .. description .. "</li>"
end

-- Основная функция 
function p.reagentRow(frame)
    local args       = frame.args
    local reagentId  = args.id or ""
    if reagentId == "" then
        return [[<tr><td colspan="2">'''Ошибка: не указан ID реагента.'''</td></tr>]]
    end

    local reagentEntry
    for _, r in ipairs(plantData) do
        if r.id == reagentId then reagentEntry = r; break end
    end

    local chemEntry
    for _, c in ipairs(chemData) do
        if c.id == reagentId then chemEntry = c; break end
    end

	local entry = chemData[reagentId]
    local reagentName = entry and entry.name or reagentId
    local reagentCell = string.format("! [[Химия#chem_%s|%s]]", reagentId, reagentName)

    local fragments = {}

    if reagentEntry and type(reagentEntry.plantMetabolism) == 'table' then
        for _, eff in ipairs(reagentEntry.plantMetabolism) do
            table.insert(fragments, formatEffect(eff))
        end
    end

    -- Ручное описание при вызове параметром "manualEffects"
    if args.manualEffects and args.manualEffects ~= "" then
        table.insert(fragments, args.manualEffects)
    end

    if reagentEntry and reagentEntry.chemicals then
        table.insert(fragments, formatChemicals(reagentEntry))
    end

    local allItems    = table.concat(fragments)
    local effectsCell = string.format("| <ul>%s</ul>", allItems)

    return frame:preprocess(string.format("|-\n%s\n%s", reagentCell, effectsCell))
end

return p