Модуль:Chemistry Lookup: различия между версиями

Материал из FIRE STATION WIKI
Категория:Food>Morty
м (Защитил страницу Модуль:Chemistry Lookup: Скрипты ([Редактирование=Разрешено только администраторам] (бессрочно) [Переименование=Разрешено только администраторам] (бессрочно)))
 
Нет описания правки
 
(не показаны 23 промежуточные версии 3 участников)
Строка 2: Строка 2:


local p = {}
local p = {}
p.chem = prototypes.chem
p.chem = prototypes.chem or {}
p.react = prototypes.react
p.react = prototypes.react or {}
p.groupDirection = prototypes.groupDirection
p.status = prototypes.status or {}
p.groupDirection = prototypes.groupDirection or {}
 
-- ===== Хелперы =====
local function tablelength(T)
local count = 0
for _ in pairs(T or {}) do count = count + 1 end
return count
end
 
local function hchangelist(l, frame)
local out = ""
local len = tablelength(l)
local i = 0
for k, v in pairs(l) do
i = i + 1
if len == i and i ~= 1 then
out = out .. ", and "
elseif i ~= 1 then
out = out .. ", "
end
out = out .. frame:expandTemplate{ title = "HealthModifier", args = { adj = v, kind = k } }
end
return out
end


function p.readscalar(frame)
function p.readscalar(frame)
return mw.text.nowiki(p.chem[frame.args[1]][frame.args[2]])
local a, b = frame.args[1], frame.args[2]
if not (a and b) or not p.chem[a] then return "" end
local v = p.chem[a][b]
if v == nil then return "" end
return mw.text.nowiki(tostring(v))
end
end


function p.readscalarreact(frame)
function p.readscalarreact(frame)
if p.react[frame.args[1]][frame.args[2]] ~= nil then
local a, b = frame.args[1], frame.args[2]
return mw.text.nowiki(p.react[frame.args[1]][frame.args[2]])
if not (a and b) or not p.react[a] then return "" end
else
local v = p.react[a][b]
return ""
if v == nil then return "" end
end
return mw.text.nowiki(tostring(v))
end
end


function p.getcolor(frame)
function p.getcolor(frame)
return mw.text.nowiki(p.chem[frame.args[1]].color:sub(1, 7))
local a = frame.args[1]
if not a or not p.chem[a] or not p.chem[a].color then return "" end
return mw.text.nowiki(p.chem[a].color:sub(1, 7))
end
end


function p.gettextcolor(frame)
function p.gettextcolor(frame)
local basecol = p.chem[frame.args[1]].color
local a = frame.args[1]
local red = tonumber(basecol:sub(2, 3), 16)
if not a or not p.chem[a] or not p.chem[a].color then return mw.text.nowiki("#000") end
local grn = tonumber(basecol:sub(4, 5), 16)
local basecol = p.chem[a].color
local blu = tonumber(basecol:sub(6, 7), 16)
local red = tonumber(basecol:sub(2, 3), 16) or 0
local grn = tonumber(basecol:sub(4, 5), 16) or 0
local blu = tonumber(basecol:sub(6, 7), 16) or 0
local luminance = math.sqrt(0.241*red*red + 0.691*grn*grn + 0.068*blu*blu)
local luminance = math.sqrt(0.241*red*red + 0.691*grn*grn + 0.068*blu*blu)
if luminance > 100 then
if luminance > 100 then
Строка 36: Строка 68:


function p.hasrecipe(frame)
function p.hasrecipe(frame)
return p.chem[frame.args[1]]["recipes"][1] ~= nil
local chem = frame.args[1]
if not chem or not p.chem[chem] then return "" end
return (p.chem[chem].recipes and p.chem[chem].recipes[1]) and "true" or ""
end
end


Строка 42: Строка 76:
local out = ""
local out = ""
local group = frame.args[1]
local group = frame.args[1]
for k in pairs(p.chem) do
for k, v in pairs(p.chem) do
if p.chem[k].group == group then
if type(v) == "table" then
out = out .. frame:expandTemplate{ title = "Chembox", args = { prototype = k }}
if (group == nil) or (v.group == group) then
elseif group == nil then
out = out .. frame:expandTemplate{ title = "Chembox", args = { prototype = k }}
out = out .. frame:expandTemplate{ title = "Chembox", args = { prototype = k }}
end
end
end
end
end
Строка 54: Строка 88:
function p.buildreactboxes(frame)
function p.buildreactboxes(frame)
local out = ""
local out = ""
for k in pairs(p.react) do
for k, v in pairs(p.react) do
if tablelength(p.react[k].effects) ~= 0 then
if type(v) == "table" and v.effects and tablelength(v.effects) ~= 0 then
out = out .. frame:expandTemplate{ title = "Reactionbox", args = { reaction = k }}
out = out .. frame:expandTemplate{ title = "Reactionbox", args = { reaction = k }}
end
end
end
end
Строка 64: Строка 98:
function p.buildrecipes(frame)
function p.buildrecipes(frame)
local chem = frame.args[1]
local chem = frame.args[1]
if not chem or not p.chem[chem] then return "" end
local out = ""
local out = ""
for id, recipe in pairs(p.chem[chem].recipes) do
for _, recipe in pairs(p.chem[chem].recipes or {}) do
out = out .. p.buildreaction(frame, recipe)
out = out .. p.buildreaction(frame, recipe)
end
return out
end
-- Версия для консоли отладки без frame
function p.buildrecipes_debug(chem)
if not chem or not p.chem[chem] then return "Химикат не найден" end
local out = "=== Рецепты для " .. chem .. " ===\n"
for i, recipe in ipairs(p.chem[chem].recipes or {}) do
out = out .. "Рецепт " .. i .. ": " .. recipe .. "\n"
if p.react[recipe] then
local data = p.react[recipe]
out = out .. "  Реактанты:\n"
for k, v in pairs(data.reactants or {}) do
out = out .. "    - " .. k .. ": " .. (v.amount or "?") .. "\n"
end
out = out .. "  Продукты:\n"
for k, v in pairs(data.products or {}) do
out = out .. "    - " .. k .. ": " .. tostring(v) .. "\n"
end
end
out = out .. "\n"
end
end
return out
return out
Строка 77: Строка 134:


function p.buildreaction(frame, react)
function p.buildreaction(frame, react)
if not react or not p.react[react] then return "" end
-- Проверка для консоли отладки
if not frame or not frame.expandTemplate then
return "Рецепт: " .. react .. " (для полного отображения используйте в MediaWiki)"
end
local data = p.react[react]
local data = p.react[react]
local dest = "Chemistry"
local args = {}
local args = {}
-- Реактанты
local i = 0
local i = 0
for k,v in pairs(data.reactants) do
for k, v in pairs(data.reactants or {}) do
i = i + 1
i = i + 1
local dest = "Chemistry"
local dest = p.groupDirection[(p.chem[k] or {}).group] or "Chemistry"
if (p.groupDirection[p.chem[k].group] ~= nil) then
args["component-" .. i] = frame:expandTemplate{
dest = p.groupDirection[p.chem[k].group]
title = "Chem Recipe Component",
end
args = { reagent = k, amount = v.amount, dest = dest }
args["component-" .. i] = frame:expandTemplate{ title = "Chem Recipe Component", args = { reagent = k, amount = v.amount, dest = dest }}
}
end
end
-- Продукты
i = 0
i = 0
for k,v in pairs(data.products) do
for k, v in pairs(data.products or {}) do
i = i + 1
i = i + 1
local dest = "Chemistry"
local dest = p.groupDirection[(p.chem[k] or {}).group] or "Chemistry"
if (p.groupDirection[p.chem[k].group] ~= nil) then
args["result-" .. i] = frame:expandTemplate{
dest = p.groupDirection[p.chem[k].group]
title = "Chem Recipe Component",
end
args = { reagent = k, amount = v, dest = dest }
args["result-" .. i] = frame:expandTemplate{ title = "Chem Recipe Component", args = { reagent = k, amount = v, dest = dest }}
}
end
end
 
-- Эффекты реакции (не метаболизм)
if data.effects ~= nil then
if data.effects ~= nil then
args.effects = p.geneffectlist(data.effects, frame, 1)
args.effects = p.geneffectlist(data.effects, frame, 1)
Строка 104: Строка 172:


return frame:expandTemplate{ title = "Chem Box Recipe", args = args }
return frame:expandTemplate{ title = "Chem Box Recipe", args = args }
end
local function scan_metab(chem)
local met = (p.chem[chem] or {}).metabolisms
if not met then return nil end
return met
end
end


function p.checksatiatesthirst(frame)
function p.checksatiatesthirst(frame)
local chem = frame.args[1]
local chem = frame.args[1]
local met = p.chem[chem].metabolisms
local met = scan_metab(chem)
if met == nil then
if not met then return "" end
return ""
for _, v in pairs(met) do
end
for _, w in pairs(v.effects or {}) do
for k, v in pairs(met) do
-- Исправляем проверку для JSON структуры
for l, w in pairs(v.effects) do
local effectName = (type(w.type) == "table" and w.type.name) or w.type or ""
if w.id == "SatiateThirst" then
if effectName == "SatiateThirst" then return "1" end
return "1"
end
end
end
end
end
Строка 124: Строка 196:
function p.checksatiateshunger(frame)
function p.checksatiateshunger(frame)
local chem = frame.args[1]
local chem = frame.args[1]
local met = p.chem[chem].metabolisms
local met = scan_metab(chem)
if met == nil then
if not met then return "" end
return ""
for _, v in pairs(met) do
end
for _, w in pairs(v.effects or {}) do
for k, v in pairs(met) do
-- Исправляем проверку для JSON структуры
for l, w in pairs(v.effects) do
local effectName = (type(w.type) == "table" and w.type.name) or w.type or ""
if w.id == "SatiateHunger" then
if effectName == "SatiateHunger" then return "1" end
return "1"
end
end
end
end
end
Строка 140: Строка 210:
function p.haseffects(frame)
function p.haseffects(frame)
local chem = frame.args[1]
local chem = frame.args[1]
local met = p.chem[chem].metabolisms
local met = scan_metab(chem)
if met == nil then
if not met then return "" end
return ""
for _, v in pairs(met) do
end
for _, w in pairs(v.effects or {}) do
for k, v in pairs(met) do
-- Исправляем проверку для JSON структуры
for l, w in pairs(v.effects) do
local effectName = (type(w.type) == "table" and w.type.name) or w.type or ""
if w.id ~= "SatiateHunger" and w.id ~= "SatiateThirst" then
if effectName ~= "SatiateHunger" and effectName ~= "SatiateThirst" then
return "1"
return "1"
end
end
Строка 155: Строка 225:


function p.geneffects(frame, chem)
function p.geneffects(frame, chem)
if chem == nil then
if chem == nil then chem = frame.args[1] end
chem = frame.args[1]
local met = scan_metab(chem)
end
if not met then return "" end
local met = p.chem[chem].metabolisms
if met == nil then
return ""
end
local out = ""
local out = ""
for k, v in pairs(met) do
for k, v in pairs(met) do
out = out .. "<b>" .. k .. "</b> (" .. v.rate .. " единиц в секунду)\n" .. p.geneffectlist(v.effects, frame, v.rate)
-- Исправляем вывод rate - теперь используем правильное поле
local rate = v.rate or 1.0
-- Получаем локализованное название группы метаболизма
local groupName = k
if p.status and p.status[k] and p.status[k].name then
groupName = p.status[k].name
end
out = out .. "<b>" .. groupName .. "</b>\n"
-- Генерируем эффекты для этой группы
local effectsText = p.geneffectlist(v.effects or {}, frame, rate)
out = out .. effectsText
out = out .. "\n"
end
end
return out
return out
Строка 171: Строка 251:
function p.geneffectlist(effects, frame, rate)
function p.geneffectlist(effects, frame, rate)
local out = ""
local out = ""
for l, w in pairs(effects) do
for _, w in pairs(effects or {}) do
-- Popup Message is ignored on purpose
-- Исправляем получение ID эффекта для JSON структуры
if w.id == "HealthChange" then
local effectId = (type(w.type) == "table" and w.type.name) or w.type or w.id or ""
out = out .. ":" .. p.genhealthchange(w, rate, frame) .. "\n"
elseif w.id == "AdjustReagent" then
-- Обрабатываем условия для всех эффектов
out = out .. ":" .. p.genadjustreagent(w, rate, frame) .. "\n"
local conditionsText = ""
elseif w.id == "FlammableReaction" then
if w.conditions then
out = out .. ":" .. p.genflammablereaction(w, frame) .. "\n"
-- Проверяем есть ли хотя бы одно условие
elseif w.id == "AdjustTemperature" then
local hasConditions = false
out = out .. ":" .. p.genadjusttemperature(w, frame) .. "\n"
for _ in pairs(w.conditions) do
elseif w.id == "GenericStatusEffect" then
hasConditions = true
out = out .. ":" .. p.gengenericstatuseffect(w, frame) .. "\n"
break
elseif w.id == "ExplosionReactionEffect" then
end
out = out .. ":" .. p.genexplosionreactioneffect(w, frame) .. "\n"
if hasConditions then
elseif w.id == "FoamAreaReactionEffect" then
conditionsText = " если " .. p.genconds(w.conditions, frame or {})
out = out .. ":" .. p.genfoamareareactioneffect(w, frame) .. "\n"
end
elseif w.id == "SmokeAreaReactionEffect" then
end
out = out .. ":" .. p.gensmokeareareactioneffect(w, frame) .. "\n"
elseif w.id == "ModifyBleedAmount" then
-- Применяем factor ко всем эффектам
out = out .. ":" .. p.genmodifybleedamount(w, frame) .. "\n"
local factor = w.factor or 1
local effectText = ""
if effectId == "SatiateThirst" then
local text = (type(w.type) == "table" and w.type.text) or "Утоляет жажду"
if factor ~= 1 then
effectText = text .. " на " .. tostring(factor) .. "x от обычного"
else
effectText = text
end
elseif effectId == "SatiateHunger" then
local text = (type(w.type) == "table" and w.type.text) or "Утоляет голод"
if factor ~= 1 then
effectText = text .. " на " .. tostring(factor) .. "x от обычного"
else
effectText = text
end
elseif effectId == "HealthChange" then
effectText = p.genhealthchange(w, rate, frame or {})
elseif effectId == "AdjustReagent" then
effectText = p.genadjustreagent(w, rate, frame or {})
-- Добавьте другие типы эффектов по необходимости
end
if effectText ~= "" then
out = out .. effectText .. conditionsText .. "\n"
end
end
end
end
return out
return out
end
end


function p.gensmokeareareactioneffect(r, frame)
function p.gensmokeareareactioneffect(r, frame)
local conds = nil
if r.conditions ~= nil then  
if r.conditions ~= nil then  
conds = p.genconds(r.conditions, frame)
conds = p.genconds(r.conditions, frame)
Строка 204: Строка 314:


function p.genfoamareareactioneffect(r, frame)
function p.genfoamareareactioneffect(r, frame)
local conds = nil
if r.conditions ~= nil then  
if r.conditions ~= nil then  
conds = p.genconds(r.conditions, frame)
conds = p.genconds(r.conditions, frame)
Строка 211: Строка 322:


function p.genexplosionreactioneffect(r, frame)
function p.genexplosionreactioneffect(r, frame)
local conds = nil
if r.conditions ~= nil then  
if r.conditions ~= nil then  
conds = p.genconds(r.conditions, frame)
conds = p.genconds(r.conditions, frame)
Строка 218: Строка 330:


function p.gengenericstatuseffect(r, frame)
function p.gengenericstatuseffect(r, frame)
local conds = nil
if r.conditions ~= nil then  
if r.conditions ~= nil then  
conds = p.genconds(r.conditions, frame)
conds = p.genconds(r.conditions, frame)
end
end
return frame:expandTemplate{ title = "GenericStatusEffect", args = { key = r.Key, type = r.Type, time = r.Time, refresh = r.Refresh, when = conds, prob = r.probability }}
return frame:expandTemplate{
title = "GenericStatusEffect",
args = { key = r.Key or r.key, type = r.Type, time = r.Time or r.time, refresh = r.Refresh, when = conds, prob = r.probability }
}
end
end


function p.genadjusttemperature(r, frame)
function p.genadjusttemperature(r, frame)
local conds = nil
if r.conditions ~= nil then  
if r.conditions ~= nil then  
conds = p.genconds(r.conditions, frame)
conds = p.genconds(r.conditions, frame)
end
end
return frame:expandTemplate{ title = "AdjustTemperature", args = { amount = r.Amount, when = conds, prob = r.probability }}
return frame:expandTemplate{ title = "AdjustTemperature", args = { amount = r.Amount or r.amount, when = conds, prob = r.probability }}
end
 
function p.genflammablereaction(r, frame)
if r.conditions ~= nil then
conds = p.genconds(r.conditions, frame)
end
return frame:expandTemplate{ title = "FlammableReaction", args = { multiplier = r.Multiplier, when = conds, prob = r.probability }}
end
end


function p.genflammablereaction(r, frame)
function p.genflammablereaction(r, frame)
local conds = nil
if r.conditions ~= nil then  
if r.conditions ~= nil then  
conds = p.genconds(r.conditions, frame)
conds = p.genconds(r.conditions, frame)
Строка 246: Строка 357:


function p.genadjustreagent(r, rate, frame)
function p.genadjustreagent(r, rate, frame)
if r.conditions ~= nil then  
local factor = r.factor or 1
conds = p.genconds(r.conditions, frame)
local amount = (r.amount or r.Amount or 0) * factor
local reagent = r.reagent or r.Reagent or "неизвестный реагент"
if amount > 0 then
return "<span style='color: #4dabf7'>Добавляет " .. tostring(amount) .. " ед. " .. reagent .. "</span>"
else
return "<span style='color: #ffa8a8'>Удаляет " .. tostring(-amount) .. " ед. " .. reagent .. "</span>"
end
end
return frame:expandTemplate{ title = "AdjustReagent", args = { amount = r.Amount, reagent = r.Reagent, when = conds, prob = r.probability }}
end
end


function p.genmodifybleedamount(r, frame)
function p.genmodifybleedamount(r, frame)
local conds = nil
if r.conditions ~= nil then  
if r.conditions ~= nil then  
conds = p.genconds(r.conditions, frame)
conds = p.genconds(r.conditions, frame)
end
end
return frame:expandTemplate{ title = "ModifyBleedAmount", args = { amount = r.Amount, when = conds, prob = r.probability }}
return frame:expandTemplate{ title = "ModifyBleedAmount", args = { amount = r.Amount or r.amount, when = conds, prob = r.probability }}
end
end


function p.genhealthchange(h, rate, frame)
function p.genhealthchange(h, rate, frame)
local healst = {}
local effects = {}
local dealst = {}
local factor = h.factor or 1
local r = 1.0 / rate
if h.damage.types ~= nil then
if h.damage and h.damage.types then
for k, v in pairs(h.damage.types) do
for damageType, amount in pairs(h.damage.types) do
if v < 0 then
local finalAmount = amount * factor
healst[k] = v * r
if finalAmount > 0 then
else
table.insert(effects, "<span style='color: #ff6b6b'>Наносит " .. tostring(finalAmount) .. " ед. " .. damageType .. "</span>")
dealst[k] = v * r
else
table.insert(effects, "<span style='color: #51cf66'>Лечит " .. tostring(-finalAmount) .. " ед. " .. damageType .. "</span>")
end
end
end
end
end
end
if h.damage.groups ~= nil then
if h.damage and h.damage.groups then
for k, v in pairs(h.damage.groups) do
for damageGroup, amount in pairs(h.damage.groups) do
if v < 0 then
local finalAmount = amount * factor
healst[k] = v * r
if finalAmount > 0 then
else
table.insert(effects, "<span style='color: #ff6b6b'>Наносит " .. tostring(finalAmount) .. " ед. " .. damageGroup .. "</span>")
dealst[k] = v * r
else
table.insert(effects, "<span style='color: #51cf66'>Лечит " .. tostring(-finalAmount) .. " ед. " .. damageGroup .. "</span>")
end
end
end
end
end
end
local heals = hchangelist(healst, frame)
return table.concat(effects, "<br/>")
local deals = hchangelist(dealst, frame)
local conds = nil
if h.conditions ~= nil then
conds = p.genconds(h.conditions, frame)
end
return frame:expandTemplate{ title = "HealthChange", args = { heals = heals, deals = deals, when = conds, prob = h.probability }}
end
 
function hchangelist(l, frame)
out = ""
local len = tablelength(l)
local i = 0
for k, v in pairs(l) do
i = i + 1
if len == i and i ~= 1 then
out = out .. ", and "
elseif i ~= 1 then
out = out .. ", "
end
out = out .. hchange(k, v, frame)
end
return out
end
 
-- So we can make it fancy later
function hchange(ty, amnt, frame)
return frame:expandTemplate{ title = "HealthModifier", args = { adj = amnt, kind = ty } }
end
end


function p.genconds(conds, frame)
function p.genconds(conds, frame)
out = ""
local out = ""
local len = tablelength(conds)
local len = tablelength(conds or {})
local i = 0
local i = 0
for k, v in pairs(conds) do
for _, c in pairs(conds or {}) do
i = i + 1
i = i + 1
if len == i and i ~= 1 then
if len == i and i ~= 1 then
Строка 324: Строка 416:
out = out .. ", "
out = out .. ", "
end
end
out = out .. p.gencond(v, frame)
out = out .. p.gencond(c, frame)
end
end
return out
return out
Строка 330: Строка 422:


function p.gencond(c, frame)
function p.gencond(c, frame)
if c.id == "TotalDamage" then
if not c or not c.type then return "" end
return frame:expandTemplate{ title = "TotalDamage", args = { min = c.Min, max = c.Max } }
if c.type == "TotalDamage" then
elseif c.id == "ReagentThreshold" then
-- Если нет frame, формируем текст напрямую
return frame:expandTemplate{ title = "ReagentThreshold", args = { min = c.Min, max = c.Max, reagent = c.Reagent } }
if not frame or not frame.expandTemplate then
elseif c.id == "OrganType" then
local min = c.Min or c.min or "?"
return frame:expandTemplate{ title = "OrganType", args = { shouldhave = c.ShouldHave, type = c.Type } }
local max = c.Max or c.max or "?"
elseif c.id == "Temperature" then
return "общий урон между " .. tostring(min) .. " и " .. tostring(max)
return frame:expandTemplate{ title = "Temperature", args = { min = c.Min, max = c.Max } }
end
return frame:expandTemplate{ title = "TotalDamage", args = { min = c.Min or c.min, max = c.Max or c.max } }
elseif c.type == "ReagentThreshold" then
-- Если нет frame, формируем текст напрямую
if not frame or not frame.expandTemplate then
local min = c.Min or c.min or 0
local max = c.Max or c.max or "∞"
local reagent = c.Reagent or c.reagent or "неизвестный реагент"
return reagent .. " между " .. tostring(min) .. " и " .. tostring(max) .. " единиц"
end
return frame:expandTemplate{ title = "ReagentThreshold", args = { min = c.Min or c.min, max = c.Max or c.max, reagent = c.Reagent or c.reagent } }
elseif c.type == "Temperature" then
-- Если нет frame, формируем текст напрямую
if not frame or not frame.expandTemplate then
local min = c.Min or c.min or "?"
local max = c.Max or c.max or "?"
return "температура между " .. tostring(min) .. " и " .. tostring(max)
end
return frame:expandTemplate{ title = "Temperature", args = { min = c.Min or c.min, max = c.Max or c.max } }
else
-- Новая логика: если type не является стандартным условием, то это тип органа
local organTypeName = c.type
local shouldHave = c.shouldHave
if shouldHave == nil then shouldHave = true end
-- Получаем локализованное название типа органа из status данных
if p.status and p.status[organTypeName] and p.status[organTypeName].name then
organTypeName = p.status[organTypeName].name
end
-- Формируем текст условия напрямую
if shouldHave then
return "метаболизирующий орган это " .. organTypeName .. " орган"
else
return "метаболизирующий орган не " .. organTypeName .. " орган"
end
end
end
return ""
return ""
end
end


function tablelength(T)
-- Отладочная функция для проверки рецептов
  local count = 0
function p.debugrecipes(frame)
  for _ in pairs(T) do count = count + 1 end
local chem = frame.args[1]
  return count
if not chem then return "Не указан химикат" end
end
 
local out = "=== Отладка рецептов для " .. chem .. " ===\n"
function has_value(tab, val)
    for index, value in ipairs(tab) do
-- Проверяем существует ли химикат
        if value[1] == val then
if not p.chem[chem] then
            return true
out = out .. "ОШИБКА: Химикат не найден в базе данных\n"
        end
return out
    end
end
 
    return false
-- Проверяем есть ли рецепты
end
local recipes = p.chem[chem].recipes
 
if not recipes then
function strsplit(inputstr, seperator)
out = out .. "Рецепты не найдены (recipes = nil)\n"
        if seperator == nil then
-- Попробуем найти рецепты вручную
                seperator = ","
out = out .. "Поиск рецептов в реакциях:\n"
        end
for reactId, reactData in pairs(p.react) do
        local t={}
if reactData.products and reactData.products[chem] then
        for str in string.gmatch(inputstr, "([^"..seperator.."]+)") do
out = out .. "- Найдена реакция: " .. reactId .. " (производит " .. tostring(reactData.products[chem]) .. ")\n"
                table.insert(t, str)
end
        end
end
        return t
else
-- Подсчитываем рецепты правильно
local recipeCount = 0
for _ in pairs(recipes) do
recipeCount = recipeCount + 1
end
out = out .. "Найдено рецептов: " .. recipeCount .. "\n"
for i, recipe in ipairs(recipes) do
out = out .. "- Рецепт " .. i .. ": " .. recipe .. "\n"
if p.react[recipe] then
out = out .. " Реакция существует: да\n"
if p.react[recipe].products and p.react[recipe].products[chem] then
out = out .. "  Производит " .. chem .. ": " .. tostring(p.react[recipe].products[chem]) .. "\n"
else
out = out .. "  ОШИБКА: Не производит " .. chem .. "\n"
end
else
out = out .. "  ОШИБКА: Реакция не существует\n"
end
end
end
return out
end
end


return p
return p

Текущая версия от 00:14, 7 сентября 2025

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

local prototypes = mw.loadData("Module:Chemistry Lookup/data")

local p = {}
p.chem = prototypes.chem or {}
p.react = prototypes.react or {}
p.status = prototypes.status or {}
p.groupDirection = prototypes.groupDirection or {}

-- ===== Хелперы =====
local function tablelength(T)
	local count = 0
	for _ in pairs(T or {}) do count = count + 1 end
	return count
end

local function hchangelist(l, frame)
	local out = ""
	local len = tablelength(l)
	local i = 0
	for k, v in pairs(l) do
		i = i + 1
		if len == i and i ~= 1 then
			out = out .. ", and "
		elseif i ~= 1 then
			out = out .. ", "
		end
		out = out .. frame:expandTemplate{ title = "HealthModifier", args = { adj = v, kind = k } }
	end
	return out
end

function p.readscalar(frame)
	local a, b = frame.args[1], frame.args[2]
	if not (a and b) or not p.chem[a] then return "" end
	local v = p.chem[a][b]
	if v == nil then return "" end
	return mw.text.nowiki(tostring(v))
end

function p.readscalarreact(frame)
	local a, b = frame.args[1], frame.args[2]
	if not (a and b) or not p.react[a] then return "" end
	local v = p.react[a][b]
	if v == nil then return "" end
	return mw.text.nowiki(tostring(v))
end

function p.getcolor(frame)
	local a = frame.args[1]
	if not a or not p.chem[a] or not p.chem[a].color then return "" end
	return mw.text.nowiki(p.chem[a].color:sub(1, 7))
end

function p.gettextcolor(frame)
	local a = frame.args[1]
	if not a or not p.chem[a] or not p.chem[a].color then return mw.text.nowiki("#000") end
	local basecol = p.chem[a].color
	local red = tonumber(basecol:sub(2, 3), 16) or 0
	local grn = tonumber(basecol:sub(4, 5), 16) or 0
	local blu = tonumber(basecol:sub(6, 7), 16) or 0
	local luminance = math.sqrt(0.241*red*red + 0.691*grn*grn + 0.068*blu*blu)
	if luminance > 100 then
		return mw.text.nowiki("#000")
	else
		return mw.text.nowiki("#FFF")
	end
end

function p.hasrecipe(frame)
	local chem = frame.args[1]
	if not chem or not p.chem[chem] then return "" end
	return (p.chem[chem].recipes and p.chem[chem].recipes[1]) and "true" or ""
end

function p.buildboxes(frame)
	local out = ""
	local group = frame.args[1]
	for k, v in pairs(p.chem) do
		if type(v) == "table" then
			if (group == nil) or (v.group == group) then
				out = out .. frame:expandTemplate{ title = "Chembox", args = { prototype = k }}
			end
		end
	end
	return out
end

function p.buildreactboxes(frame)
	local out = ""
	for k, v in pairs(p.react) do
		if type(v) == "table" and v.effects and tablelength(v.effects) ~= 0 then
			out = out .. frame:expandTemplate{ title = "Reactionbox", args = { reaction = k }}
		end
	end
	return out
end

function p.buildrecipes(frame)
	local chem = frame.args[1]
	if not chem or not p.chem[chem] then return "" end
	local out = ""
	for _, recipe in pairs(p.chem[chem].recipes or {}) do
		out = out .. p.buildreaction(frame, recipe)
	end
	return out
end

-- Версия для консоли отладки без frame
function p.buildrecipes_debug(chem)
	if not chem or not p.chem[chem] then return "Химикат не найден" end
	local out = "=== Рецепты для " .. chem .. " ===\n"
	for i, recipe in ipairs(p.chem[chem].recipes or {}) do
		out = out .. "Рецепт " .. i .. ": " .. recipe .. "\n"
		if p.react[recipe] then
			local data = p.react[recipe]
			out = out .. "  Реактанты:\n"
			for k, v in pairs(data.reactants or {}) do
				out = out .. "    - " .. k .. ": " .. (v.amount or "?") .. "\n"
			end
			out = out .. "  Продукты:\n"
			for k, v in pairs(data.products or {}) do
				out = out .. "    - " .. k .. ": " .. tostring(v) .. "\n"
			end
		end
		out = out .. "\n"
	end
	return out
end

function p.buildreactionext(frame)
	local react = frame.args[1]
	return p.buildreaction(frame, react)
end

function p.buildreaction(frame, react)
	if not react or not p.react[react] then return "" end
	
	-- Проверка для консоли отладки
	if not frame or not frame.expandTemplate then
		return "Рецепт: " .. react .. " (для полного отображения используйте в MediaWiki)"
	end
	
	local data = p.react[react]
	local args = {}

	-- Реактанты
	local i = 0
	for k, v in pairs(data.reactants or {}) do
		i = i + 1
		local dest = p.groupDirection[(p.chem[k] or {}).group] or "Chemistry"
		args["component-" .. i] = frame:expandTemplate{
			title = "Chem Recipe Component",
			args = { reagent = k, amount = v.amount, dest = dest }
		}
	end

	-- Продукты
	i = 0
	for k, v in pairs(data.products or {}) do
		i = i + 1
		local dest = p.groupDirection[(p.chem[k] or {}).group] or "Chemistry"
		args["result-" .. i] = frame:expandTemplate{
			title = "Chem Recipe Component",
			args = { reagent = k, amount = v, dest = dest }
		}
	end

	-- Эффекты реакции (не метаболизм)
	if data.effects ~= nil then
		args.effects = p.geneffectlist(data.effects, frame, 1)
	end

	return frame:expandTemplate{ title = "Chem Box Recipe", args = args }
end

local function scan_metab(chem)
	local met = (p.chem[chem] or {}).metabolisms
	if not met then return nil end
	return met
end

function p.checksatiatesthirst(frame)
	local chem = frame.args[1]
	local met = scan_metab(chem)
	if not met then return "" end
	for _, v in pairs(met) do
		for _, w in pairs(v.effects or {}) do
			-- Исправляем проверку для JSON структуры
			local effectName = (type(w.type) == "table" and w.type.name) or w.type or ""
			if effectName == "SatiateThirst" then return "1" end
		end
	end
	return ""
end

function p.checksatiateshunger(frame)
	local chem = frame.args[1]
	local met = scan_metab(chem)
	if not met then return "" end
	for _, v in pairs(met) do
		for _, w in pairs(v.effects or {}) do
			-- Исправляем проверку для JSON структуры
			local effectName = (type(w.type) == "table" and w.type.name) or w.type or ""
			if effectName == "SatiateHunger" then return "1" end
		end
	end
	return ""
end

function p.haseffects(frame)
	local chem = frame.args[1]
	local met = scan_metab(chem)
	if not met then return "" end
	for _, v in pairs(met) do
		for _, w in pairs(v.effects or {}) do
			-- Исправляем проверку для JSON структуры
			local effectName = (type(w.type) == "table" and w.type.name) or w.type or ""
			if effectName ~= "SatiateHunger" and effectName ~= "SatiateThirst" then
				return "1"
			end
		end
	end
	return ""
end

function p.geneffects(frame, chem)
	if chem == nil then chem = frame.args[1] end
	local met = scan_metab(chem)
	if not met then return "" end
	local out = ""
	for k, v in pairs(met) do
		-- Исправляем вывод rate - теперь используем правильное поле
		local rate = v.rate or 1.0
		
		-- Получаем локализованное название группы метаболизма
		local groupName = k
		if p.status and p.status[k] and p.status[k].name then
			groupName = p.status[k].name
		end
		
		out = out .. "<b>" .. groupName .. "</b>\n"
		
		-- Генерируем эффекты для этой группы
		local effectsText = p.geneffectlist(v.effects or {}, frame, rate)
		out = out .. effectsText
		out = out .. "\n"
	end
	return out
end

function p.geneffectlist(effects, frame, rate)
	local out = ""
	for _, w in pairs(effects or {}) do
		-- Исправляем получение ID эффекта для JSON структуры
		local effectId = (type(w.type) == "table" and w.type.name) or w.type or w.id or ""
		
		-- Обрабатываем условия для всех эффектов
		local conditionsText = ""
		if w.conditions then
			-- Проверяем есть ли хотя бы одно условие
			local hasConditions = false
			for _ in pairs(w.conditions) do
				hasConditions = true
				break
			end
			if hasConditions then
				conditionsText = " если " .. p.genconds(w.conditions, frame or {})
			end
		end
		
		-- Применяем factor ко всем эффектам
		local factor = w.factor or 1
		local effectText = ""
		
		if effectId == "SatiateThirst" then
			local text = (type(w.type) == "table" and w.type.text) or "Утоляет жажду"
			if factor ~= 1 then
				effectText = text .. " на " .. tostring(factor) .. "x от обычного"
			else
				effectText = text
			end
		elseif effectId == "SatiateHunger" then
			local text = (type(w.type) == "table" and w.type.text) or "Утоляет голод"
			if factor ~= 1 then
				effectText = text .. " на " .. tostring(factor) .. "x от обычного"
			else
				effectText = text
			end
		elseif effectId == "HealthChange" then
			effectText = p.genhealthchange(w, rate, frame or {})
		elseif effectId == "AdjustReagent" then
			effectText = p.genadjustreagent(w, rate, frame or {})
		-- Добавьте другие типы эффектов по необходимости
		end
		
		if effectText ~= "" then
			out = out .. effectText .. conditionsText .. "\n"
		end
	end
	return out
end





function p.gensmokeareareactioneffect(r, frame)
	local conds = nil
	if r.conditions ~= nil then 
		conds = p.genconds(r.conditions, frame)
	end
	return frame:expandTemplate{ title = "SmokeAreaReactionEffect", args = { when = conds, prob = r.probability }}
end

function p.genfoamareareactioneffect(r, frame)
	local conds = nil
	if r.conditions ~= nil then 
		conds = p.genconds(r.conditions, frame)
	end
	return frame:expandTemplate{ title = "FoamAreaReactionEffect", args = { when = conds, prob = r.probability }}
end

function p.genexplosionreactioneffect(r, frame)
	local conds = nil
	if r.conditions ~= nil then 
		conds = p.genconds(r.conditions, frame)
	end
	return frame:expandTemplate{ title = "ExplosionReactionEffect", args = { when = conds, prob = r.probability }}
end

function p.gengenericstatuseffect(r, frame)
	local conds = nil
	if r.conditions ~= nil then 
		conds = p.genconds(r.conditions, frame)
	end
	return frame:expandTemplate{
		title = "GenericStatusEffect",
		args = { key = r.Key or r.key, type = r.Type, time = r.Time or r.time, refresh = r.Refresh, when = conds, prob = r.probability }
	}
end

function p.genadjusttemperature(r, frame)
	local conds = nil
	if r.conditions ~= nil then 
		conds = p.genconds(r.conditions, frame)
	end
	return frame:expandTemplate{ title = "AdjustTemperature", args = { amount = r.Amount or r.amount, when = conds, prob = r.probability }}
end

function p.genflammablereaction(r, frame)
	local conds = nil
	if r.conditions ~= nil then 
		conds = p.genconds(r.conditions, frame)
	end
	return frame:expandTemplate{ title = "FlammableReaction", args = { multiplier = r.Multiplier, when = conds, prob = r.probability }}
end

function p.genadjustreagent(r, rate, frame)
	local factor = r.factor or 1
	local amount = (r.amount or r.Amount or 0) * factor
	local reagent = r.reagent or r.Reagent or "неизвестный реагент"
	
	if amount > 0 then
		return "<span style='color: #4dabf7'>Добавляет " .. tostring(amount) .. " ед. " .. reagent .. "</span>"
	else
		return "<span style='color: #ffa8a8'>Удаляет " .. tostring(-amount) .. " ед. " .. reagent .. "</span>"
	end
end

function p.genmodifybleedamount(r, frame)
	local conds = nil
	if r.conditions ~= nil then 
		conds = p.genconds(r.conditions, frame)
	end
	return frame:expandTemplate{ title = "ModifyBleedAmount", args = { amount = r.Amount or r.amount, when = conds, prob = r.probability }}
end

function p.genhealthchange(h, rate, frame)
	local effects = {}
	local factor = h.factor or 1
	
	if h.damage and h.damage.types then
		for damageType, amount in pairs(h.damage.types) do
			local finalAmount = amount * factor
			if finalAmount > 0 then
				table.insert(effects, "<span style='color: #ff6b6b'>Наносит " .. tostring(finalAmount) .. " ед. " .. damageType .. "</span>")
			else
				table.insert(effects, "<span style='color: #51cf66'>Лечит " .. tostring(-finalAmount) .. " ед. " .. damageType .. "</span>")
			end
		end
	end
	
	if h.damage and h.damage.groups then
		for damageGroup, amount in pairs(h.damage.groups) do
			local finalAmount = amount * factor
			if finalAmount > 0 then
				table.insert(effects, "<span style='color: #ff6b6b'>Наносит " .. tostring(finalAmount) .. " ед. " .. damageGroup .. "</span>")
			else
				table.insert(effects, "<span style='color: #51cf66'>Лечит " .. tostring(-finalAmount) .. " ед. " .. damageGroup .. "</span>")
			end
		end
	end
	
	return table.concat(effects, "<br/>")
end

function p.genconds(conds, frame)
	local out = ""
	local len = tablelength(conds or {})
	local i = 0
	for _, c in pairs(conds or {}) do
		i = i + 1
		if len == i and i ~= 1 then
			out = out .. ", and "
		elseif i ~= 1 then
			out = out .. ", "
		end
		out = out .. p.gencond(c, frame)
	end
	return out
end

function p.gencond(c, frame)
	if not c or not c.type then return "" end
	if c.type == "TotalDamage" then
		-- Если нет frame, формируем текст напрямую
		if not frame or not frame.expandTemplate then
			local min = c.Min or c.min or "?"
			local max = c.Max or c.max or "?"
			return "общий урон между " .. tostring(min) .. " и " .. tostring(max)
		end
		return frame:expandTemplate{ title = "TotalDamage", args = { min = c.Min or c.min, max = c.Max or c.max } }
	elseif c.type == "ReagentThreshold" then
		-- Если нет frame, формируем текст напрямую
		if not frame or not frame.expandTemplate then
			local min = c.Min or c.min or 0
			local max = c.Max or c.max or "∞"
			local reagent = c.Reagent or c.reagent or "неизвестный реагент"
			return reagent .. " между " .. tostring(min) .. " и " .. tostring(max) .. " единиц"
		end
		return frame:expandTemplate{ title = "ReagentThreshold", args = { min = c.Min or c.min, max = c.Max or c.max, reagent = c.Reagent or c.reagent } }
	elseif c.type == "Temperature" then
		-- Если нет frame, формируем текст напрямую
		if not frame or not frame.expandTemplate then
			local min = c.Min or c.min or "?"
			local max = c.Max or c.max or "?"
			return "температура между " .. tostring(min) .. " и " .. tostring(max)
		end
		return frame:expandTemplate{ title = "Temperature", args = { min = c.Min or c.min, max = c.Max or c.max } }
	else
		-- Новая логика: если type не является стандартным условием, то это тип органа
		local organTypeName = c.type
		local shouldHave = c.shouldHave
		if shouldHave == nil then shouldHave = true end
		
		-- Получаем локализованное название типа органа из status данных
		if p.status and p.status[organTypeName] and p.status[organTypeName].name then
			organTypeName = p.status[organTypeName].name
		end
		
		-- Формируем текст условия напрямую
		if shouldHave then
			return "метаболизирующий орган это " .. organTypeName .. " орган"
		else
			return "метаболизирующий орган не " .. organTypeName .. " орган"
		end
	end
	return ""
end

-- Отладочная функция для проверки рецептов
function p.debugrecipes(frame)
	local chem = frame.args[1]
	if not chem then return "Не указан химикат" end
	
	local out = "=== Отладка рецептов для " .. chem .. " ===\n"
	
	-- Проверяем существует ли химикат
	if not p.chem[chem] then
		out = out .. "ОШИБКА: Химикат не найден в базе данных\n"
		return out
	end
	
	-- Проверяем есть ли рецепты
	local recipes = p.chem[chem].recipes
	if not recipes then
		out = out .. "Рецепты не найдены (recipes = nil)\n"
		-- Попробуем найти рецепты вручную
		out = out .. "Поиск рецептов в реакциях:\n"
		for reactId, reactData in pairs(p.react) do
			if reactData.products and reactData.products[chem] then
				out = out .. "- Найдена реакция: " .. reactId .. " (производит " .. tostring(reactData.products[chem]) .. ")\n"
			end
		end
	else
		-- Подсчитываем рецепты правильно
		local recipeCount = 0
		for _ in pairs(recipes) do
			recipeCount = recipeCount + 1
		end
		out = out .. "Найдено рецептов: " .. recipeCount .. "\n"
		
		for i, recipe in ipairs(recipes) do
			out = out .. "- Рецепт " .. i .. ": " .. recipe .. "\n"
			if p.react[recipe] then
				out = out .. "  Реакция существует: да\n"
				if p.react[recipe].products and p.react[recipe].products[chem] then
					out = out .. "  Производит " .. chem .. ": " .. tostring(p.react[recipe].products[chem]) .. "\n"
				else
					out = out .. "  ОШИБКА: Не производит " .. chem .. "\n"
				end
			else
				out = out .. "  ОШИБКА: Реакция не существует\n"
			end
		end
	end
	
	return out
end

return p