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

мНет описания правки
мНет описания правки
 
(не показано 358 промежуточных версий этого же участника)
Строка 1: Строка 1:
local p = {}
local p = {}


-- Функция для загрузки данных исследований из JSON-файла
-- Загрузка данных
local function loadResearchData()
local chemData = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data")
local content = mw.title.new("User:IanComradeBot/Песочница.json"):getContent()
local seedsData = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data")
if not content then
 
return nil
local function kelvinToCelsius(k)
end
    return k - 273.15
return mw.text.jsonDecode(content)
end
end


-- Функция для поиска исследований по дисциплине
local function findSeedById(id, data)
local function findResearchByDiscipline(dataCache, discipline)
    for _, seed in ipairs(data) do
local results = {}
        if seed.id == id then
for _, research in ipairs(dataCache) do
            return seed
if research.technology and research.technology.discipline == discipline then
        end
table.insert(results, research.technology)
    end
end
    return nil
end
return results
end
end


-- Таблица для перевода названий дисциплин
local function formatCharacteristics(seed)
local disciplineMapping = {
    local parts = {
Arsenal = "Арсенал",
        ("[[Гидропоника#Потенция|Потенция]]: %s"):format(seed.potency or 1),
Industrial = "Промышленность",
        ("[[Гидропоника#Урожайность|Урожайность]]: %s"):format(seed.yield),
Experimental = "Экспериментальное",
        ("[[Гидропоника#Срок жизни|Срок жизни]]: %s"):format(seed.lifespan),
CivilianServices = "Обслуживание персонала"
        ("[[Гидропоника#Созревание|Созревание]]: %s"):format(seed.maturation),
}
        ("[[Гидропоника#Производство|Производство]]: %s"):format(seed.production),
        ("[[Гидропоника#Стадии роста|Стадии роста]]: %s"):format(seed.growthStages or 6),
    }
    return table.concat(parts, '<br>')
end


-- Таблица для цветов по уровням
local function formatConditions(seed)
local tierColors = {
    local parts = {
[1] = "#54d554",
        ("[[Гидропоника#Потребление воды|Вода]]: %s"):format(seed.waterConsumption or 0.5),
[2] = "#ed9000",
        ("[[Гидропоника#Потребление нутриентов|Удобрение]]: %s"):format(seed.nutrientConsumption or 0.75),
[3] = "#d72a2a"
        ("[[Гидропоника#Оптимальная температура|Темп.]]: %.2f°C"):format(kelvinToCelsius(seed.idealHeat or 293)),
}
    }
    return table.concat(parts, '<br>')
end


function p.main(frame)
local function formatHarvestType(seed)
-- Подключение CSS
    return seed.harvestRepeat and "[[Гидропоника#Тип урожая|" .. tostring(seed.harvestRepeat) .. "]]" or "-"
local cssLink = frame:extensionTag('templatestyles', '', {
end
src = 'Шаблон:Research/styles.css'
local function formatHarvestType(seed)
})
    local harvestRepeat = seed.harvestRepeat
    if harvestRepeat == "Repeat" then
        return "[[Гидропоника#Тип урожая|Многолетнее]]"
    elseif harvestRepeat == "SelfHarvest" then
        return "[[Гидропоника#Тип урожая|Самосбор]]"
    else
        return "[[Гидропоника#Тип урожая|Однолетнее]]"
    end
end


-- Загрузка данных
local function formatChemicals(seed)
local dataCache = loadResearchData()
    if not seed.chemicals then return "-" end
if not dataCache then
    local list = {}
return cssLink .. '<div style="color:red;">Ошибка загрузки данных исследований. Проверьте файл JSON.</div>'
    for chemId, vals in pairs(seed.chemicals) do
end
        local entry = chemData[chemId]
        local chemName = entry and entry.name or chemId
        table.insert(list, string.format(
            "<li>[[Химия#chem_%s|%s]] (мин: %s, макс: %s, дел: %s)</li>",
            chemId, chemName, vals.Min or 0, vals.Max or 0, vals.PotencyDivisor or 1
        ))
    end
    return "<ul>" .. table.concat(list) .. "</ul>"
end


-- Получение дисциплины
local function formatMutations(seed, data)
local discipline = frame.args[1] or ""
    if not seed.mutationPrototypes then return "-" end
if discipline == "" then
    local list = {}
return cssLink .. '<div style="color:red;">Не указана дисциплина. Доступные дисциплины: '
    for _, mu in ipairs(seed.mutationPrototypes) do
.. table.concat(vim.tbl_keys(disciplineMapping), ", ") .. '</div>'
        local target = findSeedById(mu, data)
end
        if target and target.productPrototypes then
            for _, prod in ipairs(target.productPrototypes) do
                table.insert(list, ("<li>{{Предмет|%s|link=Гидропоника#{{#invoke:Entity Lookup|getname|%s}}}}</li>"):format(prod, prod))
            end
        end
    end
    return "<ul>" .. table.concat(list) .. "</ul>"
end


-- Инициализация строки вывода
local function generateHeader()
local out = cssLink .. '<div class="research-group">'
    return [[
{| id="BOTANY" class="wikitable sortable mw-collapsible" style="width:100%;"
! rowspan="2" style="width:10%;" | Плод
! rowspan="2" class="unsortable" style="width:5%;" | Семена
! rowspan="2" class="unsortable" style="width:5%;" | Растение
! colspan="3" class="unsortable" style="width:30%;" id="no-highlight" | Характеристики
! rowspan="2" class="unsortable" style="width:30%;" | Содержит вещества
! rowspan="2" style="width:20%;" | Мутации
|-  
! style="width:10%;" class="unsortable" | Рост
! style="width:10%;" class="unsortable" | Условия
! style="width:5%;" class="unsortable" | Тип сбора
]]
end


-- Получаем список исследований по дисциплине
local function generateFooter()
local researches = findResearchByDiscipline(dataCache, discipline)
    return "|}"
if not researches or #researches == 0 then
end
return out .. '<div style="color:red;">Нет исследований для дисциплины "' .. discipline .. '"</div></div>'
end


-- Формирование блоков исследований
function p.table(frame)
for _, tech in ipairs(researches) do
    local data = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data")
local disciplineName = disciplineMapping[tech.discipline] or "Неизвестная дисциплина"
    local rows = {}
local tierColor = tierColors[tech.tier] or "#FFFFFF"
local iconPath = tech.icon and tech.icon.sprite or nil


-- Проверка данных
    for _, seed in ipairs(data) do
if not tech.id or not tech.name then
        local prodId = seed.productPrototypes[1]
return cssLink .. '<div style="color:red;">Ошибка: отсутствует ID или имя технологии.</div>'
        local seedId = seed.packetPrototype
end
        local seedName = string.format('{{#invoke:Entity Lookup|getname|%s}}', seedId)


-- Основной блок исследования
        local anchor  = string.format('{{anchor|%s}}', seedName)
out = out .. '<div class="research" id="' .. tech.id .. '">'
        local fruitImg = string.format(
out = out .. frame:preprocess('<div class="research__images">[[Файл:{{#invoke:Entity Sprite|main|path|' .. (iconPath or "default_icon.png") .. '}}]]</div>')
            '{{Предмет|%s|size=64px|vertical=1|imageTooltip=1|link=%s}}',
out = out .. frame:preprocess('<div class="research__name">{{#invoke:Ftl|main|translation|' .. tech.name .. '}}[[Файл:' .. tech.discipline .. '.png|16px|link=]]</div>')
            prodId, seedName
out = out .. '<div class="research__type">'
        )
out = out .. '<div>Уровень: <span style="color:' .. tierColor .. ';">' .. (tech.tier or "N/A") .. '</span></div>'
        local seedImg  = string.format(
out = out .. '<div class="research__technology">' .. disciplineName .. '</div>'
            '{{Предмет|%s|size=64px|vertical=1|imageTooltip=1|l=|link=%s}}',
out = out .. '<div>Стоимость: <span style="color:#DA70D6;">' .. (tech.cost or "N/A") .. '</span></div>'
            seedId, seedName
out = out .. '</div>'
        )
        local plantImg = string.format(
            '{{Предмет|%s-harvest|size=64px|l=|link=%s}}',
            seedId, seedName
        )


-- Блок необходимых исследований
        local colGrowth    = formatCharacteristics(seed)
if tech.technologyPrerequisites and #tech.technologyPrerequisites > 0 then
        local colConditions = formatConditions(seed)
out = out .. '<div class="research__technologies-prerequisites">Необходимые исследования:'
        local colHarvest    = formatHarvestType(seed)
out = out .. '<ul>'
        local colChemicals  = formatChemicals(seed)
        local colMutations  = formatMutations(seed, data)


for _, prerequisite in ipairs(tech.technologyPrerequisites) do
        local row = frame:preprocess(string.format(
out = out .. frame:preprocess('<li>{{#invoke:Entity Lookup|getname|' .. prerequisite .. '}}</li>')
            [[|-
end
            ! %s
            ! %s
            ! %s
            | %s
            | %s
            | %s
            | %s
            | %s ]],
            fruitImg, seedImg, plantImg,
            colGrowth, colConditions, colHarvest,
            colChemicals, colMutations
        ))
        table.insert(rows, row)
    end


out = out .. '</ul>'
    return generateHeader() .. table.concat(rows, '\n') .. '\n' .. generateFooter()
out = out .. '</div>'
end
end


-- Блок открываемых рецептов
function p.main(frame)
if tech.recipeUnlocks and #tech.recipeUnlocks > 0 then
    local args = frame.args
out = out .. '<div class="research__technologies-unlocks">Разблокирует:'
    local id = args[1]
out = out .. '<ul>'
    local mode  = mw.text.trim(args[2] or ""):lower()
 
    local seed = findSeedById(id, seedsData)
for _, recipe in ipairs(tech.recipeUnlocks) do
    if not seed then return "" end
out = out .. frame:preprocess('<li>{{#invoke:Entity Lookup|getname|' .. recipe .. '}}</li>')
end
out = out .. '</ul>'
out = out .. '</div>'
end
 
out = out .. '</div>'
end


out = out .. '</div>'
    if mode  == "growth" then
return out
        return formatCharacteristics(seed)
    elseif mode  == "conditions" then
        return formatConditions(seed)
    elseif mode  == "harvest" then
        return formatHarvestType(seed)
    elseif mode  == "chemicals" then
        return formatChemicals(seed)
    elseif mode  == "mutations" then
        return formatMutations(seed, seedsData)
    else
        return ""
    end
end
end


return p
return p