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

Материал из Space Station 14 Вики
мНет описания правки
Метка: отменено
Нет описания правки
 
(не показана 61 промежуточная версия этого же участника)
Строка 1: Строка 1:
local p = {}
local p = {}
local getArgs = require('Module:Arguments').getArgs


-- Конфигурация
function p.main(frame)
local CHEM_DATA_PATH = "Модуль:IanComradeBot/prototypes/chem/plant.json/data"
     local args = getArgs(frame, { removeBlanks = false })
 
     local name = args[1] or ""
local EFFECT_TEMPLATES = {
     local attributes = args[2] or ""
    PlantAdjustNutrition = "Увеличивает [[#Потребление нутриентов|нутриенты]] на %s.",
     if name == "" then
    PlantAdjustHealth = "Изменяет [[#Здоровье|здоровье]] на %s.",
         return "<span class=\"error\">Ошибка: не указано имя файла.</span>"
    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
     end
    local ext = (args["ext"] or "png"):gsub("^%.", "")
    local namespace = args["namespace"] or "Файл"
    local max = tonumber(args["max"]) or 50
    local include_base = (args["base"] ~= "no")


     local description
     local found = {}
    if effect.amount then
        local formatted_amount = formatAmount(effect.amount)
        description = string.format(template, formatted_amount)
    else
        description = string.format(template, "")
    end


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


     return "<li>" .. description .. "</li>"
     for i = 1, max do
end
        local t = mw.title.new("Файл:" .. name .. "-" .. i .. "." .. ext)
 
        if t and t.exists then
function p.reagentRow(frame)
            table.insert(found, "-" .. i)
    local args = frame:getParent().args
        end
    local reagentId = args.id
 
    if not reagentId then
        return "<tr><td colspan='2'>'''Ошибка в модуле ReagentEffects: не указан ID реагента.'''</td></tr>"
    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


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


     local reagentName = reagent.name or reagentId
     local before = "[[" .. namespace .. ":" .. name
     local reagentCell = string.format("! [[Химия#chem_%s|%s]]", reagentId, reagentName)
     local after = "." .. ext .. "|" .. attributes .. "]]"
 
    local effectsList = {}
    if reagent.plantMetabolism then
        for _, effectData in ipairs(reagent.plantMetabolism) do
            table.insert(effectsList, formatEffect(effectData))
        end
    end


     local manualEffects = args.manual_effects
     local parts = {}
     if manualEffects and manualEffects ~= '' then
     table.insert(parts, "<choose before=\"" .. before .. "\" after=\"" .. after .. "\">")
        for line in mw.text.gsplit(manualEffects, "\n") do
    for _, suf in ipairs(found) do
            if line ~= '' then
        table.insert(parts, "<option>" .. suf .. "</option>")
                table.insert(effectsList, line)
            end
        end
     end
     end
    table.insert(parts, "</choose>")


     local effectsCell = "| " .. table.concat(effectsList, "\n")
     return frame:preprocess(table.concat(parts, "\n"))
 
    return "|-\n" .. reagentCell .. "\n" .. effectsCell
end
end


return p
return p

Текущая версия от 02:52, 17 марта 2026

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

local p = {}
local getArgs = require('Module:Arguments').getArgs

function p.main(frame)
    local args = getArgs(frame, { removeBlanks = false })
    local name = args[1] or ""
    local attributes = args[2] or ""
    if name == "" then
        return "<span class=\"error\">Ошибка: не указано имя файла.</span>"
    end
    local ext = (args["ext"] or "png"):gsub("^%.", "") 
    local namespace = args["namespace"] or "Файл"
    local max = tonumber(args["max"]) or 50
    local include_base = (args["base"] ~= "no")

    local found = {}

    if include_base then
        local t = mw.title.new("Файл:" .. name .. "." .. ext)
        if t and t.exists then
            table.insert(found, "")
        end
    end

    for i = 1, max do
        local t = mw.title.new("Файл:" .. name .. "-" .. i .. "." .. ext)
        if t and t.exists then
            table.insert(found, "-" .. i)
        end
    end

    if #found == 0 then
        return ""
    end

    local before = "[[" .. namespace .. ":" .. name
    local after = "." .. ext .. "|" .. attributes .. "]]"

    local parts = {}
    table.insert(parts, "<choose before=\"" .. before .. "\" after=\"" .. after .. "\">")
    for _, suf in ipairs(found) do
        table.insert(parts, "<option>" .. suf .. "</option>")
    end
    table.insert(parts, "</choose>")

    return frame:preprocess(table.concat(parts, "\n"))
end

return p