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

мНет описания правки
Метка: отменено
Нет описания правки
 
(не показано 60 промежуточных версий этого же участника)
Строка 1: Строка 1:
local p = {}
local p = {}
local getArgs = require('Module:Arguments').getArgs


local plantData = mw.loadData("Модуль:IanComradeBot/prototypes/chem/plant.json/data")
function p.main(frame)
local chemData = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data")
    local args = getArgs(frame, { removeBlanks = false })
 
    local name = args[1] or ""
-- Шаблоны описания эффектов
     local attributes = args[2] or ""
local EFFECT_TEMPLATES = {
     if name == "" then
    PlantAdjustPotency      = "Изменяет [[#Потенция|потенцию]] на %s.",
         return "<span class=\"error\">Ошибка: не указано имя файла.</span>"
     PlantAdjustHealth        = "Изменяет [[#Здоровье|здоровье]] на %s.",
     end
     PlantAdjustNutrition    = "Изменяет [[#Потребление нутриентов|нутриенты]] на %s.",
     local ext = (args["ext"] or "png"):gsub("^%.", "")
    PlantAdjustWater         = "Изменяет [[#Потребление воды|воду]] на %s.",
     local namespace = args["namespace"] or "Файл"
     PlantAdjustToxins        = "Изменяет [[#Устойчивость к токсинам|токсины]] на %s.",
     local max = tonumber(args["max"]) or 50
     PlantAdjustPests        = "Изменяет [[#Защита от вредителей|вредителей]] на %s.",
     local include_base = (args["base"] ~= "no")
    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 found = {}
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]
     if include_base then
    local description
         local t = mw.title.new("Файл:" .. name .. "." .. ext)
     if template then
        if t and t.exists then
         if effect.amount then
             table.insert(found, "")
            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
         end
    else
        description = string.format("<code>Неизвестный эффект: %s</code>", effectType)
     end
     end


     if effect.probability and effect.probability < 1 then
     for i = 1, max do
         local pct = tostring(effect.probability * 100)
         local t = mw.title.new("Файл:" .. name .. "-" .. i .. "." .. ext)
         description = string.format("С шансом '''%s %%:''' %s", pct, description:sub(1,1):lower() .. description:sub(2))
         if t and t.exists then
            table.insert(found, "-" .. i)
        end
     end
     end


    return "<li>" .. description .. "</li>"
     if #found == 0 then
end
         return ""
 
-- Основная функция
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
     end


     local reagentEntry
     local before = "[[" .. namespace .. ":" .. name
     for _, r in ipairs(plantData) do
     local after = "." .. ext .. "|" .. attributes .. "]]"
        if r.id == reagentId then reagentEntry = r; break end
    end


     local chemEntry
     local parts = {}
     for _, c in ipairs(chemData) do
    table.insert(parts, "<choose before=\"" .. before .. "\" after=\"" .. after .. "\">")
         if c.id == reagentId then chemEntry = c; break end
     for _, suf in ipairs(found) do
         table.insert(parts, "<option>" .. suf .. "</option>")
     end
     end
    table.insert(parts, "</choose>")


local entry = chemData[reagentId]
     return frame:preprocess(table.concat(parts, "\n"))
    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
end


return p
return p