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

мНет описания правки
Метка: отменено
мНет описания правки
Метка: отменено
Строка 1: Строка 1:
-- Загрузка данных
local p = {}
local accentData = mw.loadData("Модуль:IanComradeBot/prototypes/accent.json/data")


local p = {}
-- Конфигурация
local CHEM_DATA_PATH = "Модуль:IanComradeBot/prototypes/chem/plant.json/data"
 
local EFFECT_TEMPLATES = {
    PlantAdjustNutrition = "Увеличивает [[#Потребление нутриентов|нутриенты]] на %s.",
    PlantAdjustHealth = "Изменяет [[#Здоровье|здоровье]] на %s.",
    PlantAdjustMutationMod = "Изменяет '''модификатор мутации''' на %s.",
    PlantAdjustToxins = "Увеличивает [[#Устойчивость к токсинам|токсины]] на %s.",
    PlantAdjustPests = "Уменьшает [[#Защита от вредителей|вредителей]] на %s.",
    PlantAdjustWeeds = "Уменьшает [[#Защита от сорняков|сорняки]] на %s.",
    PlantAdjustPotency = "Изменяет [[#Потенция|потенцию]] на %s.",
    PlantAffectGrowth = "Увеличивает [[#Возраст|возраст]] на %s.",
    PlantAdjustWater = "Изменяет [[#Потребление воды|воду]] на %s.",
    PlantAdjustMutationLevel = "Увеличивает '''уровень мутации''' на %s.",
    -- Для более сложных эффектов лучше использовать параметр manual_effects
    PlantRestoreSeeds = "Восстанавливает семена (делает растение не [[#Бесплодное|бесплодным]], если оно было таковым).",
    PlantDestroySeeds = "Уничтожает семена (делает растение [[#Бесплодное|бесплодным]]).",
    PlantPhalanximine = "Делает растение жизнеспособным (если оно было нежизнеспособным).",
    PlantCryoxadone = "Уменьшает возраст растения.",
    RobustHarvest = "Запускает специфический эффект 'Робаст харвест'.",
    PlantDiethylamine = "Запускает специфический эффект 'Диэтиламин'."
}
 
-- Вспомогательные функции
local function formatAmount(amount)
    local color = amount > 0 and "good" or "bad"
    return string.format("{{цвет|text|%s|c='''%s'''}}", color, tostring(amount))
end
 
local function formatEffect(effect)
    local effectType = effect.type:gsub("!type:", "")
    local template = EFFECT_TEMPLATES[effectType]
 
    if not template then
        return "<li>Неизвестный эффект: " .. effectType .. "</li>"
    end
 
    local description
    if effect.amount then
        local formatted_amount = formatAmount(effect.amount)
        description = string.format(template, formatted_amount)
    else
        description = string.format(template, "")
    end


function p.table(frame)
    if effect.probability and effect.probability < 1 then
    local targetId = frame.args[1] or ""
        local chance = tostring(effect.probability * 100)
    if targetId == "" then
        description = string.format("С шансом '''%s %%''' %s", chance, mw.ustring.lower(mw.ustring.sub(description, 1, 1)) .. mw.ustring.sub(description, 2))
        return "Ошибка: не указан параметр id."
     end
     end


     local foundData = nil
    return "<li>" .. description .. "</li>"
end
 
function p.reagentRow(frame)
     local args = frame:getParent().args
    local reagentId = args.id


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


     if not foundData then
    local reagent = chemData[reagentId]
         return "Ошибка: данные по id '" .. targetId .. "' не найдены."
     if not reagent then
         return string.format("<tr><td colspan='2'>'''Ошибка: реагент с ID '%s' не найден в базе данных.'''</td></tr>", reagentId)
     end
     end


     local output = {}
     local reagentName = reagent.name or reagentId
table.insert(output, '{| class="sortable-grid sortable-grid--small-column sortable"')
    local reagentCell = string.format("! [[Химия#chem_%s|%s]]", reagentId, reagentName)
table.insert(output, '! Сортировка (по алфавиту)')
table.insert(output, '|-')


for key, value in pairs(foundData.wordReplacements) do
    local effectsList = {}
local keyData = "{{#invoke:Ftl|main|translation|".. key .."}}"
    if reagent.plantMetabolism then
local valueData = "{{#invoke:Ftl|main|translation|".. value .."}}"
        for _, effectData in ipairs(reagent.plantMetabolism) do
    if keyData ~= "Ошибка: Ключ не найден." and valueData ~= "Ошибка: Ключ не найден." then
            table.insert(effectsList, formatEffect(effectData))
        table.insert(output, "|")
        end
        table.insert(
    end
            output,
 
            frame:preprocess(
    local manualEffects = args.manual_effects
                string.format(
    if manualEffects and manualEffects ~= '' then
                    "{{Cut-Layout|arrow=1|background-color=var(--bg-color-message-subtle)|%s|%s}}",
        for line in mw.text.gsplit(manualEffects, "\n") do
                    keyData,
            if line ~= '' then
                    valueData
                table.insert(effectsList, line)
                )
            end
            )
        end
        )
    end
        table.insert(output, "|-")
    end
end


table.insert(output, '|}')
    local effectsCell = "| " .. table.concat(effectsList, "\n")


     return table.concat(output, "\n")
     return "|-\n" .. reagentCell .. "\n" .. effectsCell
end
end


return p
return p