Модуль:Prototypes/Химия/Растения: различия между версиями

Материал из Space Station 14 Вики
Новая страница: «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 = "Изменяет здоровье на...»
 
Нет описания правки
 
(не показаны 2 промежуточные версии этого же участника)
Строка 1: Строка 1:
local p = {}
local p = {}


local plantData = mw.loadData("Модуль:IanComradeBot/prototypes/chem/plant.json/data")
-- Загрузка данных
local chemData = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data")
local plantData = mw.loadData("Module:IanComradeBot/prototypes/chem/plant.json/data")
local chemData = mw.loadData("Module:IanComradeBot/chem prototypes.json/data")


-- Шаблоны описания эффектов
-- Вспомогательная функция
local EFFECT_TEMPLATES = {
local function formatEffect(effect, frame)
    PlantAdjustPotency      = "Изменяет [[#Потенция|потенцию]] на %s.",
local rawType = effect['!type']
    PlantAdjustHealth        = "Изменяет [[#Здоровье|здоровье]] на %s.",
if not rawType then
    PlantAdjustNutrition    = "Изменяет [[#Потребление нутриентов|нутриенты]] на %s.",
return "<li>Ошибка: не найден тип эффекта.</li>"
    PlantAdjustWater        = "Изменяет [[#Потребление воды|воду]] на %s.",
end
    PlantAdjustToxins        = "Изменяет [[#Устойчивость к токсинам|токсины]] на %s.",
local effectType = rawType:gsub("%s*%b{}", "")
    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 formattedAmount = ""
    local rawType = effect['!type']
if effect.amount then
    if not rawType then return "<li>Ошибка: не найден тип эффекта.</li>" end
local num = tonumber(effect.amount)
    local effectType = rawType:gsub("%s*%b{}", "")
local color = num and (num > 0 and "good" or "bad") or "text"
local amt  = num and ((num > 0) and ("+" .. num) or tostring(num)) or tostring(effect.amount)
formattedAmount = string.format("{{цвет|text|%s|c='''%s'''}}", color, amt)
end


    local template = EFFECT_TEMPLATES[effectType]
-- Вызываем шаблон для основного описания
    local description
local tpl = string.format("{{Prototypes/Химия/Растения/base|%s|%s}}", effectType, formattedAmount)
    if template then
local description = frame:preprocess(tpl)
        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)
if effect.probability and effect.probability < 1 then
        description = string.format("С шансом '''%s %%:''' %s", pct, description:sub(1,1):lower() .. description:sub(2))
local pct = tostring(effect.probability * 100)
    end
description = string.format("С шансом '''%s %%''' %s", pct, description:sub(1,1):lower() .. description:sub(2))
end


    return "<li>" .. description .. "</li>"
return "<li>{{ucfirst:" .. description .. "}}</li>"
end
end


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


    local reagentEntry
-- Поиск записей в данных
    for _, r in ipairs(plantData) do
local reagentEntry
        if r.id == reagentId then reagentEntry = r; break end
for _, r in ipairs(plantData) do
    end
if r.id == reagentId then reagentEntry = r; break end
end
local chemEntry = chemData[reagentId]


    local chemEntry
local reagentName = chemEntry and chemEntry.name or reagentId
    for _, c in ipairs(chemData) do
local reagentCell = string.format("! [[Химия#chem_%s|%s]]", reagentId, reagentName)
        if c.id == reagentId then chemEntry = c; break end
    end


local entry = chemData[reagentId]
local fragments = {}
    local reagentName = entry and entry.name or reagentId
if reagentEntry and type(reagentEntry.plantMetabolism) == 'table' then
    local reagentCell = string.format("! [[Химия#chem_%s|%s]]", reagentId, reagentName)
for _, eff in ipairs(reagentEntry.plantMetabolism) do
table.insert(fragments, formatEffect(eff, frame))
end
end


    local fragments = {}
if args.manualEffects and args.manualEffects ~= "" then
table.insert(fragments, args.manualEffects)
end


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


    -- Ручное описание при вызове параметром "manualEffects"
local effectsCell = string.format("| <ul>%s</ul>", table.concat(fragments))
    if args.manualEffects and args.manualEffects ~= "" then
return frame:preprocess(string.format("|-\n%s\n%s", reagentCell, effectsCell))
        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

Текущая версия от 18:24, 5 августа 2025

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

local p = {}

-- Загрузка данных
local plantData = mw.loadData("Module:IanComradeBot/prototypes/chem/plant.json/data")
local chemData  = mw.loadData("Module:IanComradeBot/chem prototypes.json/data")

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

	-- Форматируем значение, если есть
	local formattedAmount = ""
	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 ((num > 0) and ("+" .. num) or tostring(num)) or tostring(effect.amount)
		formattedAmount = string.format("{{цвет|text|%s|c='''%s'''}}", color, amt)
	end

	-- Вызываем шаблон для основного описания
	local tpl = string.format("{{Prototypes/Химия/Растения/base|%s|%s}}", effectType, formattedAmount)
	local description = frame:preprocess(tpl)

	-- Обрабатываем вероятность
	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>{{ucfirst:" .. 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 = chemData[reagentId]

	local reagentName = chemEntry and chemEntry.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, frame))
		end
	end

	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 effectsCell = string.format("| <ul>%s</ul>", table.concat(fragments))
	return frame:preprocess(string.format("|-\n%s\n%s", reagentCell, effectsCell))
end

return p