|
|
| (не показано 275 промежуточных версий этого же участника) |
| Строка 1: |
Строка 1: |
| | local p = {} |
| | |
| -- Загрузка данных | | -- Загрузка данных |
| local dataModule = mw.loadData("Модуль:Prototypes/Хранилище/Предмет/data") | | local chemData = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data") |
| local itemData = dataModule.Item | | local seedsData = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data") |
| local allSelectorData = dataModule.AllSelector
| |
| | |
| local p = {}
| |
|
| |
|
| -- Функция processRolls для преобразования диапазона
| | local function kelvinToCelsius(k) |
| local processRolls = function(rolls) | | return k - 273.15 |
| local result = {} | |
| if rolls and rolls.range then
| |
| local min, max = rolls.range:match("(%d+),%s*(%d+)")
| |
| min, max = tonumber(min), tonumber(max)
| |
| if min and max then
| |
| result[#result + 1] = string.format('[%d-%d]', min + 1, max + 1)
| |
| else
| |
| result[#result + 1] = 'Некорректный формат для range.'
| |
| end
| |
| elseif rolls and rolls.value then
| |
| result[#result + 1] = string.format('[%d]', rolls.value)
| |
| else
| |
| result[#result + 1] = 'Не указан параметр rolls.'
| |
| end
| |
| return table.concat(result)
| |
| end | | end |
|
| |
|
| -- Поиск данных по ID
| | local function findSeedById(id, data) |
| local function findDataById(data, id) | | for _, seed in ipairs(data) do |
| for _, item in ipairs(data) do | | if seed.id == id then |
| if item.id == id then | | return seed |
| return item | |
| end | | end |
| end | | end |
| Строка 35: |
Строка 18: |
| end | | end |
|
| |
|
| -- Форматирование содержимого
| | local function formatCharacteristics(seed) |
| local function formatContent(content) | | local parts = { |
| if not content.id then | | ("[[Гидропоника#Потенция|Потенция]]: %s"):format(seed.potency or 1), |
| return "Ошибка: отсутствует id у элемента." | | ("[[Гидропоника#Урожайность|Урожайность]]: %s"):format(seed.yield), |
| end
| | ("[[Гидропоника#Срок жизни|Срок жизни]]: %s"):format(seed.lifespan), |
| | | ("[[Гидропоника#Созревание|Созревание]]: %s"):format(seed.maturation), |
| local name = string.format('{{#invoke:Entity Lookup|getname|%s}}', content.id)
| | ("[[Гидропоника#Производство|Производство]]: %s"):format(seed.production), |
| local image = string.format('%s.png', content.id)
| | ("[[Гидропоника#Стадии роста|Стадии роста]]: %s"):format(seed.growthStages or 6), |
| local amount = (content.amount and content.amount ~= 1) and string.format(" [%d]", content.amount) or ""
| | } |
| local prob = "" | | return table.concat(parts, '<br>') |
| | | end |
| if content.weight then | |
| content.prob = content.weight / 100
| |
| end
| |
|
| |
|
| if content.prob then | | local function formatConditions(seed) |
| prob = string.format(" <div>%s%%</div>", content.prob * 100 >= 1 and math.floor(content.prob * 100) or content.prob * 100) | | local parts = { |
| end
| | ("[[Гидропоника#Потребление воды|Вода]]: %s"):format(seed.waterConsumption or 0.5), |
| | | ("[[Гидропоника#Потребление нутриентов|Удобрение]]: %s"):format(seed.nutrientConsumption or 0.75), |
| return string.format(
| | ("[[Гидропоника#Оптимальная температура|Темп.]]: %.2f°C"):format(kelvinToCelsius(seed.idealHeat or 293)), |
| '{{LinkСard|SideStyle=1|background-color=#cbcbff0b|image=%s|name=%s%s%s {{#invoke:Prototypes/Хранилище/Предмет|main|framing|contained|%s}} }}', | | } |
| image, name, amount, prob, content.id
| | return table.concat(parts, '<br>') |
| ) | |
| end | | end |
|
| |
|
| -- Локальные функции
| | local function formatHarvestType(seed) |
| local loadData, findDataById, formatContent, getContentsOutput, processNestedSelectors, getTableOutput, getContainedOutput, getChemOutput, handleGroupSelector, handleAllSelector, handleNestedSelector | | return seed.harvestRepeat and "[[Гидропоника#Тип урожая|" .. tostring(seed.harvestRepeat) .. "]]" or "-" |
| | |
| -- Получение содержимого через таблицу
| |
| getContentsOutput = function(contents)
| |
| local result = {} | |
| for _, content in ipairs(contents) do
| |
| result[#result + 1] = formatContent(content)
| |
| end
| |
| return table.concat(result)
| |
| end | | end |
| | | local function formatHarvestType(seed) |
| -- Обработка вложенных таблиц
| | local harvestRepeat = seed.harvestRepeat |
| processNestedSelectors = function(children)
| | if harvestRepeat == "Repeat" then |
| if not children or #children == 0 then return "" end | | return "[[Гидропоника#Тип урожая|Многолетнее]]" |
| | | elseif harvestRepeat == "SelfHarvest" then |
| local results = {}
| | return "[[Гидропоника#Тип урожая|Самосбор]]" |
| local nestedCache = {}
| | else |
| | | return "[[Гидропоника#Тип урожая|Однолетнее]]" |
| for _, child in ipairs(children) do
| |
| if child.id then | |
| results[#results + 1] = formatContent(child)
| |
| elseif child["!type"] == "NestedSelector" then
| |
| -- Кэшируем результат вызова handleNestedSelector
| |
| if not nestedCache[child.tableId] then
| |
| nestedCache[child.tableId] = handleNestedSelector(child, true)
| |
| end
| |
| results[#results + 1] = nestedCache[child.tableId]
| |
| elseif child["!type"] == "GroupSelector" then | |
| results[#results + 1] = handleGroupSelector(child)
| |
| end
| |
| end | | end |
|
| |
| return table.concat(results)
| |
| end | | end |
|
| |
|
| -- Обработка таблиц
| | local function formatChemicals(seed) |
| getTableOutput = function(tableId)
| | if not seed.chemicals then return "-" end |
| local allSelectors = loadData('User:IanComradeBot/prototypes/AllSelector.json') | | local list = {} |
| local tableData = findDataById(buildIndex(allSelectors), tableId)
| | for chemId, vals in pairs(seed.chemicals) do |
| | | local entry = chemData[chemId] |
| if not tableData then return 'Таблица не найдена.' end
| | local chemName = entry and entry.name or chemId |
| | | table.insert(list, string.format( |
| if tableData['!type:GroupSelector'] then
| | "<li>[[Химия#chem_%s|%s]] (мин: %s, макс: %s, дел: %s)</li>", |
| return handleGroupSelector(tableData['!type:GroupSelector'])
| | chemId, chemName, vals.Min or 0, vals.Max or 0, vals.PotencyDivisor or 1 |
| elseif tableData['!type:AllSelector'] then
| | )) |
| return processNestedSelectors(tableData['!type:AllSelector'].children) | |
| end | | end |
| | | return "<ul>" .. table.concat(list) .. "</ul>" |
| return 'Таблица не содержит элементов.' | |
| end | | end |
|
| |
|
| -- Формирование списка содержащихся предметов или таблиц
| | local function formatMutations(seed, data) |
| getContainedOutput = function(data, id)
| | if not seed.mutationPrototypes then return "-" end |
| local item = findDataById(data, id)
| | local list = {} |
| if not item then return '' end | | for _, mu in ipairs(seed.mutationPrototypes) do |
| | | local target = findSeedById(mu, data) |
| local result = {} | | if target and target.productPrototypes then |
| | | for _, prod in ipairs(target.productPrototypes) do |
| -- Обработка StorageFill | | table.insert(list, ("<li>{{Предмет|%s|link=Гидропоника#{{#invoke:Entity Lookup|getname|%s}}}}</li>"):format(prod, prod)) |
| if item.StorageFill and item.StorageFill.contents then
| |
| result[#result + 1] = getContentsOutput(item.StorageFill.contents)
| |
| | |
| -- Обработка EntityTableContainerFill
| |
| elseif item.EntityTableContainerFill and item.EntityTableContainerFill.containers then
| |
| local containers = item.EntityTableContainerFill.containers | |
| | |
| -- Обработка entity_storage
| |
| if containers.entity_storage then | |
| if containers.entity_storage.children then | |
| result[#result + 1] = processNestedSelectors(containers.entity_storage.children)
| |
| end
| |
| | |
| if containers.entity_storage.tableId then
| |
| result[#result + 1] = getTableOutput(containers.entity_storage.tableId)
| |
| end | | end |
| end
| |
|
| |
| -- Обработка storagebase
| |
| if containers.storagebase and containers.storagebase.tableId then
| |
| result[#result + 1] = getTableOutput(containers.storagebase.tableId)
| |
| end | | end |
| end | | end |
| | return "<ul>" .. table.concat(list) .. "</ul>" |
| | end |
|
| |
|
| return table.concat(result) | | local function generateHeader() |
| | 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 | | end |
|
| |
|
| -- Обработка AllSelector
| | local function generateFooter() |
| handleAllSelector = function(allSelector)
| | return "|}" |
| if not allSelector.children then return '' end
| |
| return processNestedSelectors(allSelector.children) | |
| end | | end |
|
| |
|
| -- Обработка GroupSelector
| | function p.table(frame) |
| handleGroupSelector = function(groupSelector)
| | local data = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data") |
| if not groupSelector.children then return '' end | | local rows = {} |
| local result = {} | |
| local wrapperStart, wrapperEnd = "", ""
| |
|
| |
|
| -- Проверка для контейнера EntityTableContainerFill | | for _, seed in ipairs(data) do |
| if groupSelector.weight and groupSelector.weight ~= "default" then
| | local prodId = seed.productPrototypes[1] |
| wrapperStart = string.format('{{LinkСard/Сollapsible|name=Группа предметов %s%%|content=', groupSelector.weight) | | local seedId = seed.packetPrototype |
| wrapperEnd = "}}"
| | local seedName = string.format('{{#invoke:Entity Lookup|getname|%s}}', seedId) |
| elseif groupSelector["!type"] == "GroupSelector" and not groupSelector.weight then
| |
| wrapperStart = '{{LinkСard/Сollapsible|name=Может выпасть лишь один из:|content='
| |
| wrapperEnd = "}}"
| |
| end
| |
|
| |
|
| for _, child in ipairs(groupSelector.children) do
| | local anchor = string.format('{{anchor|%s}}', seedName) |
| if child["!type"] == "GroupSelector" then | | local fruitImg = string.format( |
| result[#result + 1] = handleGroupSelector(child) | | '{{Предмет|%s|size=64px|vertical=1|imageTooltip=1|link=%s}}', |
| elseif child["!type"] == "AllSelector" then | | prodId, seedName |
| result[#result + 1] = string.format('{{LinkСard/Сollapsible|name=Выпадают только вместе:|content=%s}}', handleAllSelector(child))
| | ) |
| elseif child.id then | | local seedImg = string.format( |
| result[#result + 1] = formatContent(child) | | '{{Предмет|%s|size=64px|vertical=1|imageTooltip=1|l=|link=%s}}', |
| else
| | seedId, seedName |
| result[#result + 1] = "<div>Ошибка: отсутствует id у элемента.</div>" | | ) |
| end | | local plantImg = string.format( |
| end
| | '{{Предмет|%s-harvest|size=64px|l=|link=%s}}', |
| | seedId, seedName |
| | ) |
|
| |
|
| return wrapperStart .. table.concat(result) .. wrapperEnd | | local colGrowth = formatCharacteristics(seed) |
| end
| | local colConditions = formatConditions(seed) |
| | | local colHarvest = formatHarvestType(seed) |
| -- Обработка NestedSelector
| | local colChemicals = formatChemicals(seed) |
| handleNestedSelector = function(nestedSelector, wrapped)
| | local colMutations = formatMutations(seed, data) |
| if not nestedSelector.tableId then return '' end
| |
| | |
| local result = {}
| |
|
| |
|
| local classesRolls, classesProb
| | local row = frame:preprocess(string.format( |
| | | [[|- |
| if wrapped then
| | ! %s |
| if nestedSelector.rolls and nestedSelector.rolls.range then
| | ! %s |
| local rollsResult = processRolls(nestedSelector.rolls)
| | ! %s |
| if rollsResult and #rollsResult > 0 then
| | | %s |
| classesRolls = ', максимум может выпасть: ' .. rollsResult
| | | %s |
| end
| | | %s |
| end
| | | %s |
| if nestedSelector.prob then
| | | %s ]], |
| classesProb = string.format(" <div>%s%%</div>", nestedSelector.prob * 100 >= 1 and math.floor(nestedSelector.prob * 100) or nestedSelector.prob * 100) | | fruitImg, seedImg, plantImg, |
| end | | colGrowth, colConditions, colHarvest, |
| | colChemicals, colMutations |
| | )) |
| | table.insert(rows, row) |
| end | | end |
|
| |
|
| if wrapped and (classesRolls or classesProb) then
| | return generateHeader() .. table.concat(rows, '\n') .. '\n' .. generateFooter() |
| if (classesRolls and #classesRolls > 0) or (classesProb and #classesProb > 0) then
| |
| result[#result + 1] = string.format('{{LinkСard/Сollapsible|name=Группа предметов%s%s|content=', classesRolls or "", classesProb or "")
| |
| end
| |
| end
| |
| | |
| result[#result + 1] = getTableOutput(nestedSelector.tableId)
| |
| | |
| if wrapped and (classesRolls or classesProb) then
| |
| if (classesRolls and #classesRolls > 0) or (classesProb and #classesProb > 0) then
| |
| result[#result + 1] = "}}"
| |
| end
| |
| end
| |
| | |
| return table.concat(result)
| |
| end
| |
| | |
| -- Формирование списка химии
| |
| getChemOutput = function(data, id)
| |
| local item = findDataById(data, id)
| |
| if not item or not item.SolutionContainerManager or not item.SolutionContainerManager.solutions then return '' end
| |
| | |
| local result = {}
| |
| for _, solution in pairs(item.SolutionContainerManager.solutions) do
| |
| for _, reagent in ipairs(solution.reagents) do
| |
| result[#result + 1] = string.format('<li>[[Химия#chem_%s|%s]] (%d ед.)</li>', reagent.ReagentId, reagent.ReagentId, reagent.Quantity)
| |
| end
| |
| end
| |
| return string.format('<ul class="1">%s</ul>', table.concat(result))
| |
| end | | end |
|
| |
|
| -- Основная функция модуля
| |
| function p.main(frame) | | function p.main(frame) |
| local mode = frame.args[1] | | local args = frame.args |
| local id = frame.args[2] | | local id = args[1] |
| | | local mode = mw.text.trim(args[2] or ""):lower() |
| if not id then return 'Не указан ID.' end | | local seed = findSeedById(id, seedsData) |
| | | if not seed then return "" end |
| if mode == 'framing' then
| |
| local subMode = frame.args[2]
| |
| local id = frame.args[3]
| |
| | |
| if not id then
| |
| return 'Не указан ID для режима framing.'
| |
| end
| |
| | |
| if subMode == 'chem' then
| |
| return frame:preprocess('{{СollapsibleMenu|' .. getChemOutput(itemData, id) .. '}}')
| |
| elseif subMode == 'contained' then
| |
| return frame:preprocess('{{СollapsibleMenu|' .. getContainedOutput(itemData, id) .. '}}')
| |
| else
| |
| return 'Неизвестный подрежим для framing: ' .. subMode
| |
| end
| |
| elseif mode == 'chem' then | |
| return frame:preprocess(getChemOutput(itemData, id))
| |
| elseif mode == 'contained' then
| |
| return frame:preprocess(getContainedOutput(itemData, id))
| |
| elseif mode == 'rolls' then | |
| local entity = findDataById(itemData, id)
| |
| if not entity then return 'ID не найден в данных.' end
| |
| | |
| if entity.EntityTableContainerFill then
| |
| local containers = entity.EntityTableContainerFill.containers
| |
| if containers.entity_storage and containers.entity_storage.rolls then
| |
| return processRolls(containers.entity_storage.rolls)
| |
| end
| |
| end
| |
|
| |
|
| return '' | | if mode == "growth" then |
| | 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 | | else |
| return 'Неизвестный режим: ' .. mode | | return "" |
| end | | end |
| end | | end |
|
| |
|
| return p | | return p |