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

Материал из SS14 Backmen
Нет описания правки
Метка: отменено
Нет описания правки
Метка: отменено
Строка 1: Строка 1:
local prototypes = mw.loadData("Module:Chemistry Lookup/data")
-- Модуль Chemistry Lookup
local ChemistryLookup = {}


local p = {}
-- Импорт JSON-данных
p.chem = prototypes.chem
local chemData = mw.text.jsonDecode(mw.title.new("User:BKM-Head/chem_prototypes.json", "User"):getContent()) or {}
p.react = prototypes.react
p.groupDirection = prototypes.groupDirection


function p.readscalar(frame)
-- Временное хранилище для несохранённых изменений
return mw.text.nowiki(p.chem[frame.args[1]][frame.args[2]])
local tempData = {}
end


function p.readscalarreact(frame)
-- Функция для добавления временных данных
if p.react[frame.args[1]][frame.args[2]] ~= nil then
function ChemistryLookup:setTempData(prototype, field, value)
return mw.text.nowiki(p.react[frame.args[1]][frame.args[2]])
    tempData[prototype] = tempData[prototype] or {}
else
    tempData[prototype][field] = value
return ""
end
end
end


function p.getcolor(frame)
-- Функция для получения данных с учётом временных изменений
return mw.text.nowiki(p.chem[frame.args[1]].color:sub(1, 7))
function ChemistryLookup:getChemData(prototype, field)
end
    -- Проверяем временные данные
 
    if tempData[prototype] and tempData[prototype][field] then
function p.gettextcolor(frame)
        return tempData[prototype][field]
local basecol = p.chem[frame.args[1]].color
    end
local red = tonumber(basecol:sub(2, 3), 16)
    -- Если временных данных нет, возвращаем из оригинального источника
local grn = tonumber(basecol:sub(4, 5), 16)
    local chem = chemData[prototype]
local blu = tonumber(basecol:sub(6, 7), 16)
    if not chem then return nil end
local luminance = math.sqrt(0.241*red*red + 0.691*grn*grn + 0.068*blu*blu)
    return chem[field] or nil
if luminance > 100 then
return mw.text.nowiki("#000")
else
return mw.text.nowiki("#FFF")
end
end
 
function p.hasrecipe(frame)
return p.chem[frame.args[1]]["recipes"][1] ~= nil
end
 
function p.buildboxes(frame)
local out = ""
local group = frame.args[1]
for k in pairs(p.chem) do
if p.chem[k].group == group then
out = out .. frame:expandTemplate{ title = "Chembox", args = { prototype = k }}
elseif group == nil then
out = out .. frame:expandTemplate{ title = "Chembox", args = { prototype = k }}
end
end
return out
end
 
function p.buildreactboxes(frame)
local out = ""
for k in pairs(p.react) do
if tablelength(p.react[k].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]
local out = ""
for id, recipe in pairs(p.chem[chem].recipes) do
out = out .. p.buildreaction(frame, recipe)
end
return out
end
 
function p.buildreactionext(frame)
local react = frame.args[1]
return p.buildreaction(frame, react)
end
 
function p.buildreaction(frame, react)
local data = p.react[react]
local dest = "Chemistry"
local args = {}
local i = 0
for k,v in pairs(data.reactants) do
i = i + 1
local dest = "Chemistry"
if (p.groupDirection[p.chem[k].group] ~= nil) then
dest = p.groupDirection[p.chem[k].group]
end
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) do
i = i + 1
local dest = "Chemistry"
if (p.groupDirection[p.chem[k].group] ~= nil) then
dest = p.groupDirection[p.chem[k].group]
end
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
 
function p.checksatiatesthirst(frame)
local chem = frame.args[1]
local met = p.chem[chem].metabolisms
if met == nil then
return ""
end
for k, v in pairs(met) do
for l, w in pairs(v.effects) do
if w.id == "SatiateThirst" then
return "1"
end
end
end
return ""
end
 
function p.checksatiateshunger(frame)
local chem = frame.args[1]
local met = p.chem[chem].metabolisms
if met == nil then
return ""
end
for k, v in pairs(met) do
for l, w in pairs(v.effects) do
if w.id == "SatiateHunger" then
return "1"
end
end
end
return ""
end
end


function p.haseffects(frame)
-- Получение цвета реагента
local chem = frame.args[1]
function ChemistryLookup:getcolor(prototype)
local met = p.chem[chem].metabolisms
    return self:getChemData(prototype, "color") or "#000000FF"
if met == nil then
return ""
end
for k, v in pairs(met) do
for l, w in pairs(v.effects) do
if w.id ~= "SatiateHunger" and w.id ~= "SatiateThirst" then
return "1"
end
end
end
return ""
end
end


function p.geneffects(frame, chem)
-- Получение цвета текста
if chem == nil then
function ChemistryLookup:gettextcolor(prototype)
chem = frame.args[1]
    return self:getChemData(prototype, "textColor") or "#FFFFFFFF"
end
local met = p.chem[chem].metabolisms
if met == nil then
return ""
end
local out = ""
for k, v in pairs(met) do
out = out .. "<b>" .. k .. "</b> (" .. v.rate .. " единиц в секунду)\n" .. p.geneffectlist(v.effects, frame, v.rate)
end
return out
end
end


function p.geneffectlist(effects, frame, rate)
-- Получение имени реагента
local out = ""
function ChemistryLookup:getname(prototype)
for l, w in pairs(effects) do
    return self:getChemData(prototype, "name") or "Неизвестное вещество"
-- Popup Message is ignored on purpose
if w.id == "HealthChange" then
out = out .. ":" .. p.genhealthchange(w, rate, frame) .. "\n"
elseif w.id == "AdjustReagent" then
out = out .. ":" .. p.genadjustreagent(w, rate, frame) .. "\n"
elseif w.id == "FlammableReaction" then
out = out .. ":" .. p.genflammablereaction(w, frame) .. "\n"
elseif w.id == "AdjustTemperature" then
out = out .. ":" .. p.genadjusttemperature(w, frame) .. "\n"
elseif w.id == "GenericStatusEffect" then
out = out .. ":" .. p.gengenericstatuseffect(w, frame) .. "\n"
elseif w.id == "ExplosionReactionEffect" then
out = out .. ":" .. p.genexplosionreactioneffect(w, frame) .. "\n"
elseif w.id == "FoamAreaReactionEffect" then
out = out .. ":" .. p.genfoamareareactioneffect(w, frame) .. "\n"
elseif w.id == "SmokeAreaReactionEffect" then
out = out .. ":" .. p.gensmokeareareactioneffect(w, frame) .. "\n"
elseif w.id == "ModifyBleedAmount" then
out = out .. ":" .. p.genmodifybleedamount(w, frame) .. "\n"
end
end
return out
end
end


function p.gensmokeareareactioneffect(r, frame)
-- Получение описания реагента
if r.conditions ~= nil then
function ChemistryLookup:getdesc(prototype)
conds = p.genconds(r.conditions, frame)
    return self:getChemData(prototype, "desc") or "Описание отсутствует."
end
return frame:expandTemplate{ title = "SmokeAreaReactionEffect", args = { when = conds, prob = r.probability }}
end
end


function p.genfoamareareactioneffect(r, frame)
-- Проверка на наличие рецептов
if r.conditions ~= nil then
function ChemistryLookup:hasrecipe(prototype)
conds = p.genconds(r.conditions, frame)
    local recipes = self:getChemData(prototype, "recipes")
end
    return recipes and #recipes > 0
return frame:expandTemplate{ title = "FoamAreaReactionEffect", args = { when = conds, prob = r.probability }}
end
end


function p.genexplosionreactioneffect(r, frame)
-- Генерация списка рецептов
if r.conditions ~= nil then  
function ChemistryLookup:buildrecipes(prototype)
conds = p.genconds(r.conditions, frame)
    local recipes = self:getChemData(prototype, "recipes")
end
    if not recipes or #recipes == 0 then return "" end
return frame:expandTemplate{ title = "ExplosionReactionEffect", args = { when = conds, prob = r.probability }}
    return table.concat(recipes, ", ")
end
end


function p.gengenericstatuseffect(r, frame)
-- Проверка на наличие эффектов
if r.conditions ~= nil then
function ChemistryLookup:haseffects(prototype)
conds = p.genconds(r.conditions, frame)
    local metabolisms = self:getChemData(prototype, "metabolisms")
end
    return metabolisms ~= nil
return frame:expandTemplate{ title = "GenericStatusEffect", args = { key = r.Key, type = r.Type, time = r.Time, refresh = r.Refresh, when = conds, prob = r.probability }}
end
end


function p.genadjusttemperature(r, frame)
-- Генерация описания эффектов
if r.conditions ~= nil then
function ChemistryLookup:geneffects(prototype)
conds = p.genconds(r.conditions, frame)
    local metabolisms = self:getChemData(prototype, "metabolisms")
end
    if not metabolisms then return "" end
return frame:expandTemplate{ title = "AdjustTemperature", args = { amount = r.Amount, when = conds, prob = r.probability }}
end


function p.genflammablereaction(r, frame)
     local effects = {}
if r.conditions ~= nil then
     for _, metabolism in pairs(metabolisms) do
conds = p.genconds(r.conditions, frame)
         for _, effect in ipairs(metabolism.effects or {}) do
end
             table.insert(effects, effect.description or "")
return frame:expandTemplate{ title = "FlammableReaction", args = { multiplier = r.Multiplier, 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
 
function p.genadjustreagent(r, rate, frame)
if r.conditions ~= nil then
conds = p.genconds(r.conditions, frame)
end
return frame:expandTemplate{ title = "AdjustReagent", args = { amount = r.Amount, reagent = r.Reagent, when = conds, prob = r.probability }}
end
 
function p.genmodifybleedamount(r, frame)
if r.conditions ~= nil then
conds = p.genconds(r.conditions, frame)
end
return frame:expandTemplate{ title = "ModifyBleedAmount", args = { amount = r.Amount, when = conds, prob = r.probability }}
end
 
function p.genhealthchange(h, rate, frame)
     local healst = {}
     local dealst = {}
    local r = 1.0 / rate
 
    -- Проверяем существование метаболизмов и их эффектов
    if h.metabolisms and h.metabolisms.Medicine and h.metabolisms.Medicine.effects then
         for _, effect in ipairs(h.metabolisms.Medicine.effects) do
             -- Ищем эффекты с id = "HealthChange"
            if effect.id == "HealthChange" then
                print(effect.description) -- Выводим описание эффекта
            end
        end
    end
 
    -- Обработка урона по группам
    if h.damage and h.damage.groups then
        for k, v in pairs(h.damage.groups) do
            if v < 0 then
                healst[k] = v * r
            else
                dealst[k] = v * r
            end
         end
         end
     end
     end
 
     return table.concat(effects, "<br/>")
     -- Генерация списков лечения и урона
    local heals = hchangelist(healst, frame)
    local deals = hchangelist(dealst, frame)
 
    -- Обработка условий, если они есть
    local conds = nil
    if h.conditions then
        conds = p.genconds(h.conditions, frame)
    end
 
    -- Возвращаем итоговый шаблон
    return frame:expandTemplate{
        title = "HealthChange",
        args = { heals = heals, deals = deals, when = conds, prob = h.probability }
    }
end
end


 
-- Экспорт функций
function hchangelist(l, frame)
return ChemistryLookup
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
 
function p.genconds(conds, frame)
out = ""
local len = tablelength(conds)
local i = 0
for k, v in pairs(conds) 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(v, frame)
end
return out
end
 
function p.gencond(c, frame)
if c.id == "TotalDamage" then
return frame:expandTemplate{ title = "TotalDamage", args = { min = c.Min, max = c.Max } }
elseif c.id == "ReagentThreshold" then
return frame:expandTemplate{ title = "ReagentThreshold", args = { min = c.Min, max = c.Max, reagent = c.Reagent } }
elseif c.id == "OrganType" then
return frame:expandTemplate{ title = "OrganType", args = { shouldhave = c.ShouldHave, type = c.Type } }
elseif c.id == "Temperature" then
return frame:expandTemplate{ title = "Temperature", args = {  min = c.Min, max = c.Max } }
end
return ""
end
 
function tablelength(T)
  local count = 0
  for _ in pairs(T) do count = count + 1 end
  return count
end
 
function has_value(tab, val)
    for index, value in ipairs(tab) do
        if value[1] == val then
            return true
        end
    end
 
    return false
end
 
function strsplit(inputstr, seperator)
        if seperator == nil then
                seperator = ","
        end
        local t={}
        for str in string.gmatch(inputstr, "([^"..seperator.."]+)") do
                table.insert(t, str)
        end
        return t
end
 
 
return p

Версия от 11:40, 19 декабря 2024

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

-- Модуль Chemistry Lookup
local ChemistryLookup = {}

-- Импорт JSON-данных
local chemData = mw.text.jsonDecode(mw.title.new("User:BKM-Head/chem_prototypes.json", "User"):getContent()) or {}

-- Временное хранилище для несохранённых изменений
local tempData = {}

-- Функция для добавления временных данных
function ChemistryLookup:setTempData(prototype, field, value)
    tempData[prototype] = tempData[prototype] or {}
    tempData[prototype][field] = value
end

-- Функция для получения данных с учётом временных изменений
function ChemistryLookup:getChemData(prototype, field)
    -- Проверяем временные данные
    if tempData[prototype] and tempData[prototype][field] then
        return tempData[prototype][field]
    end
    -- Если временных данных нет, возвращаем из оригинального источника
    local chem = chemData[prototype]
    if not chem then return nil end
    return chem[field] or nil
end

-- Получение цвета реагента
function ChemistryLookup:getcolor(prototype)
    return self:getChemData(prototype, "color") or "#000000FF"
end

-- Получение цвета текста
function ChemistryLookup:gettextcolor(prototype)
    return self:getChemData(prototype, "textColor") or "#FFFFFFFF"
end

-- Получение имени реагента
function ChemistryLookup:getname(prototype)
    return self:getChemData(prototype, "name") or "Неизвестное вещество"
end

-- Получение описания реагента
function ChemistryLookup:getdesc(prototype)
    return self:getChemData(prototype, "desc") or "Описание отсутствует."
end

-- Проверка на наличие рецептов
function ChemistryLookup:hasrecipe(prototype)
    local recipes = self:getChemData(prototype, "recipes")
    return recipes and #recipes > 0
end

-- Генерация списка рецептов
function ChemistryLookup:buildrecipes(prototype)
    local recipes = self:getChemData(prototype, "recipes")
    if not recipes or #recipes == 0 then return "" end
    return table.concat(recipes, ", ")
end

-- Проверка на наличие эффектов
function ChemistryLookup:haseffects(prototype)
    local metabolisms = self:getChemData(prototype, "metabolisms")
    return metabolisms ~= nil
end

-- Генерация описания эффектов
function ChemistryLookup:geneffects(prototype)
    local metabolisms = self:getChemData(prototype, "metabolisms")
    if not metabolisms then return "" end

    local effects = {}
    for _, metabolism in pairs(metabolisms) do
        for _, effect in ipairs(metabolism.effects or {}) do
            table.insert(effects, effect.description or "")
        end
    end
    return table.concat(effects, "<br/>")
end

-- Экспорт функций
return ChemistryLookup