|
|
| (не показано 145 промежуточных версий этого же участника) |
| Строка 1: |
Строка 1: |
| local p = {} | | local p = {} |
|
| |
|
| ---------------------------------------------------------------------
| | -- Загрузка данных |
| -- Загрузка данных из разных модулей | | local chemData = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data") |
| ---------------------------------------------------------------------
| | local seedsData = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data") |
| local itemData = mw.loadData("Модуль:IanComradeBot/prototypes/fills/Item.json/data") | |
| local tableData = mw.loadData("Модуль:IanComradeBot/prototypes/table.json/data") | |
| local gearData = mw.loadData("Модуль:IanComradeBot/startingGear.json/data")
| |
| local jobData = mw.loadData("Модуль:IanComradeBot/job.json/data")
| |
| local gearRoleLoadout = mw.loadData("Модуль:IanComradeBot/roleLoadout.json/data")
| |
| local loadoutData = mw.loadData("Модуль:IanComradeBot/loadout.json/data")
| |
| local loadoutGroupData = mw.loadData("Модуль:IanComradeBot/loadoutGroup.json/data")
| |
| local cargoData = mw.loadData("Модуль:IanComradeBot/prototypes/сargo.json/base")
| |
| local latheData = mw.loadData("Модуль:IanComradeBot/prototypes/lathe.json/data")
| |
| local recipeData = mw.loadData("Модуль:IanComradeBot/prototypes/lathe/recipes.json/data")
| |
| local researchData = mw.loadData("Модуль:IanComradeBot/prototypes/research.json/data")
| |
| local materialData = mw.loadData("Модуль:IanComradeBot/prototypes/materials.json/data")
| |
| local chemDataLathe = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data")
| |
|
| |
|
| ---------------------------------------------------------------------
| | local function kelvinToCelsius(k) |
| -- Функции для обратного поиска | | return k - 273.15 |
| ---------------------------------------------------------------------
| | end |
|
| |
|
| -- Функция для рекурсивного поиска id предмета в произвольной структуре таблицы.
| | local function findSeedById(id, data) |
| local function searchItemInStructure(struct, targetId) | | for _, seed in ipairs(data) do |
| if type(struct) ~= "table" then
| | if seed.id == id then |
| return false
| | return seed |
| end
| |
| if struct.id and struct.id == targetId then
| |
| return true
| |
| end
| |
| for _, v in pairs(struct) do | |
| if type(v) == "table" then | |
| if searchItemInStructure(v, targetId) then | |
| return true
| |
| end
| |
| end | | end |
| end | | end |
| return false | | return nil |
| end | | end |
|
| |
|
| ---------------------------------------------------------------------
| | local function formatCharacteristics(seed) |
| -- Обратный поиск по содержимому (reverseContained)
| | local parts = { |
| -- По заданному id предмета ищем таблицы, в которых он встречается,
| | ("[[Гидропоника#Потенция|Потенция]]: %s"):format(seed.potency or 1), |
| -- а затем в itemData ищем хранилища, где используются найденные таблицы.
| | ("[[Гидропоника#Урожайность|Урожайность]]: %s"):format(seed.yield), |
| ---------------------------------------------------------------------
| | ("[[Гидропоника#Срок жизни|Срок жизни]]: %s"):format(seed.lifespan), |
| function p.reverseContained(frame)
| | ("[[Гидропоника#Созревание|Созревание]]: %s"):format(seed.maturation), |
| local targetId = frame.args[2]
| | ("[[Гидропоника#Производство|Производство]]: %s"):format(seed.production), |
| if not targetId or targetId == "" then
| | ("[[Гидропоника#Стадии роста|Стадии роста]]: %s"):format(seed.growthStages or 6), |
| return "Ошибка: не указан id предмета для обратного поиска." | | } |
| end | | return table.concat(parts, '<br>') |
| | end |
|
| |
|
| local matchingTables = {} | | local function formatConditions(seed) |
| -- Перебираем все записи таблиц
| | local parts = { |
| for tableId, tblEntry in pairs(tableData) do
| | ("[[Гидропоника#Потребление воды|Вода]]: %s"):format(seed.waterConsumption or 0.5), |
| if type(tblEntry) == "table" then | | ("[[Гидропоника#Потребление нутриентов|Удобрение]]: %s"):format(seed.nutrientConsumption or 0.75), |
| if searchItemInStructure(tblEntry, targetId) then
| | ("[[Гидропоника#Оптимальная температура|Темп.]]: %.2f°C"):format(kelvinToCelsius(seed.idealHeat or 293)), |
| table.insert(matchingTables, tableId)
| | } |
| end
| | return table.concat(parts, '<br>') |
| end
| | end |
| end
| |
|
| |
|
| if #matchingTables == 0 then | | local function formatHarvestType(seed) |
| return "Таблица, содержащая предмет с id " .. targetId .. ", не найдена." | | return seed.harvestRepeat and "[[Гидропоника#Тип урожая|" .. tostring(seed.harvestRepeat) .. "]]" or "-" |
| | end |
| | local function formatHarvestType(seed) |
| | local harvestRepeat = seed.harvestRepeat |
| | if harvestRepeat == "Repeat" then |
| | return "[[Гидропоника#Тип урожая|Многолетнее]]" |
| | elseif harvestRepeat == "SelfHarvest" then |
| | return "[[Гидропоника#Тип урожая|Самосбор]]" |
| | else |
| | return "[[Гидропоника#Тип урожая|Однолетнее]]" |
| end | | end |
| | end |
|
| |
|
| local matchingStorages = {} | | local function formatChemicals(seed) |
| -- Ищем в itemData хранилища, в которых используется найденная таблица
| | if not seed.chemicals then return "-" end |
| for storageId, storage in pairs(itemData) do | | local list = {} |
| if type(storage) == "table" and storage.EntityTableContainerFill and storage.EntityTableContainerFill.containers then | | for chemId, vals in pairs(seed.chemicals) do |
| local containers = storage.EntityTableContainerFill.containers
| | local entry = chemData[chemId] |
| if containers.entity_storage and containers.entity_storage.tableId then
| | local chemName = entry and entry.name or chemId |
| for _, tblId in ipairs(matchingTables) do
| | table.insert(list, string.format( |
| if containers.entity_storage.tableId == tblId then
| | "<li>[[Химия#chem_%s|%s]] (мин: %s, макс: %s, дел: %s)</li>", |
| table.insert(matchingStorages, storageId)
| | chemId, chemName, vals.Min or 0, vals.Max or 0, vals.PotencyDivisor or 1 |
| end
| | )) |
| end
| |
| end | |
| if containers.storagebase and containers.storagebase.tableId then | |
| for _, tblId in ipairs(matchingTables) do
| |
| if containers.storagebase.tableId == tblId then
| |
| table.insert(matchingStorages, storageId)
| |
| end
| |
| end
| |
| end
| |
| end
| |
| end | | end |
| | | return "<ul>" .. table.concat(list) .. "</ul>" |
| if #matchingStorages == 0 then | |
| return "Хранилище, вызывающее найденные таблицы, не найдено."
| |
| end
| |
| | |
| return "Найденные хранилища: " .. table.concat(matchingStorages, ", ")
| |
| end | | end |
|
| |
|
| ---------------------------------------------------------------------
| | local function formatMutations(seed, data) |
| -- Обратный поиск для экипировки (reverseEquipment)
| | if not seed.mutationPrototypes then return "-" end |
| -- По заданному id оборудования ищем, в каких наборах экипировки
| | local list = {} |
| -- оно используется, и, если найдено в startingGear, ищем в jobData
| | for _, mu in ipairs(seed.mutationPrototypes) do |
| -- по параметру startingGear, выводя id соответствующего job.
| | local target = findSeedById(mu, data) |
| ---------------------------------------------------------------------
| | if target and target.productPrototypes then |
| function p.reverseEquipment(frame)
| | for _, prod in ipairs(target.productPrototypes) do |
| local targetId = frame.args[2]
| | table.insert(list, ("<li>{{Предмет|%s|link=Гидропоника#{{#invoke:Entity Lookup|getname|%s}}}}</li>"):format(prod, prod)) |
| local slotFilter = frame.args[3] -- если указан, фильтруем по конкретному слоту
| |
| if not targetId or targetId == "" then | |
| return "Ошибка: не указан id оборудования для обратного поиска."
| |
| end
| |
| | |
| local results = {} | |
| | |
| -- Обработка startingGear (gearData)
| |
| for _, gear in pairs(gearData) do | |
| local currentGearId = gear.id or "Unknown" | |
| if gear.equipment then | |
| for slot, equipId in pairs(gear.equipment) do | |
| if equipId == targetId and (not slotFilter or slot == slotFilter) then | |
| local foundJob = nil
| |
| for jobId, job in pairs(jobData) do
| |
| if job.startingGear == currentGearId then
| |
| foundJob = jobId
| |
| break
| |
| end
| |
| end
| |
| if foundJob then
| |
| table.insert(results, "Job: " .. foundJob .. " (слот: " .. slot .. ")")
| |
| else
| |
| table.insert(results, "Gear: " .. currentGearId .. " (слот: " .. slot .. ")")
| |
| end
| |
| end
| |
| end | | end |
| end | | end |
| end | | end |
| | return "<ul>" .. table.concat(list) .. "</ul>" |
| | end |
|
| |
|
| -- Обработка loadout (loadoutData)
| | local function generateHeader() |
| for _, loadout in ipairs(loadoutData) do | | return [[ |
| if loadout.equipment then
| | {| id="BOTANY" class="wikitable sortable mw-collapsible" style="width:100%;" |
| for slot, equipId in pairs(loadout.equipment) do
| | ! rowspan="2" style="width:10%;" | Плод |
| if equipId == targetId and (not slotFilter or slot == slotFilter) then
| | ! rowspan="2" class="unsortable" style="width:5%;" | Семена |
| local foundGroupId = nil
| | ! rowspan="2" class="unsortable" style="width:5%;" | Растение |
| -- Поиск группы в loadoutGroupData, в которой присутствует loadout.id
| | ! colspan="3" class="unsortable" style="width:30%;" id="no-highlight" | Характеристики |
| for _, group in ipairs(loadoutGroupData) do
| | ! rowspan="2" class="unsortable" style="width:30%;" | Содержит вещества |
| if group.loadouts then
| | ! rowspan="2" style="width:20%;" | Мутации |
| for _, lId in ipairs(group.loadouts) do
| | |- |
| if lId == loadout.id then
| | ! style="width:10%;" class="unsortable" | Рост |
| foundGroupId = group.id
| | ! style="width:10%;" class="unsortable" | Условия |
| break
| | ! style="width:5%;" class="unsortable" | Тип сбора |
| end
| | ]] |
| end
| |
| end
| |
| if foundGroupId then break end
| |
| end
| |
| local foundJob = nil
| |
| -- Поиск роли в gearRoleLoadout, где группы содержат найденный id группы
| |
| if foundGroupId then
| |
| for _, role in pairs(gearRoleLoadout) do
| |
| if role.groups then
| |
| for _, g in ipairs(role.groups) do
| |
| if g == foundGroupId then
| |
| foundJob = role.id -- предполагается, что поле id присутствует
| |
| break
| |
| end
| |
| end
| |
| end
| |
| if foundJob then break end
| |
| end
| |
| end
| |
| if foundJob then
| |
| table.insert(results, "Job: " .. foundJob .. " (слот: " .. slot .. ")")
| |
| else
| |
| table.insert(results, "Loadout: " .. loadout.id .. " (слот: " .. slot .. ")")
| |
| end
| |
| end
| |
| end
| |
| end
| |
| end
| |
| | |
| if #results == 0 then
| |
| return "Оборудование с id " .. targetId .. " не найдено в наборах экипировки."
| |
| end
| |
| | |
| return "Найдено использование оборудования: " .. table.concat(results, "; ")
| |
| end | | end |
|
| |
|
| ---------------------------------------------------------------------
| | local function generateFooter() |
| -- Обратный поиск для груза (cargo) (reverseCargo)
| | return "|}" |
| -- Всегда осуществляется поиск по полю product.
| |
| ---------------------------------------------------------------------
| |
| function p.reverseCargo(frame) | |
| local searchValue = frame.args[2] | |
| if not searchValue or searchValue == "" then
| |
| return "Ошибка: не указано значение для поиска в режиме cargo."
| |
| end
| |
| | |
| local foundIds = {}
| |
| for _, entry in ipairs(cargoData) do
| |
| if entry.product == searchValue then
| |
| table.insert(foundIds, entry.id)
| |
| end
| |
| end
| |
| | |
| if #foundIds == 0 then
| |
| return "Запись для product со значением '" .. searchValue .. "' не найдена."
| |
| end
| |
| | |
| return "Найденные записи cargo: " .. table.concat(foundIds, ", ")
| |
| end | | end |
|
| |
|
| ---------------------------------------------------------------------
| | function p.table(frame) |
| -- Обратный поиск для станков (lathe) (reverseLathe)
| | local data = mw.loadData("Модуль:IanComradeBot/prototypes/seeds.json/data") |
| -- По заданному результату рецепта ищем рецепты станков и возвращаем id станка, который его производит.
| | local rows = {} |
| ---------------------------------------------------------------------
| |
| local function getRecipeById(recipeId)
| |
| for _, recipe in ipairs(recipeData) do | |
| if recipe.id == recipeId then
| |
| return recipe
| |
| end
| |
| end
| |
| return nil
| |
| end
| |
|
| |
|
| function p.reverseLathe(frame)
| | for _, seed in ipairs(data) do |
| local targetResult = frame.args[2]
| | local prodId = seed.productPrototypes[1] |
| if not targetResult or targetResult == "" then
| | local seedId = seed.packetPrototype |
| return "Ошибка: не указан результат рецепта для обратного поиска." | | local seedName = string.format('{{#invoke:Entity Lookup|getname|%s}}', seedId) |
| end
| |
|
| |
|
| local matchingLathes = {}
| | local anchor = string.format('{{anchor|%s}}', seedName) |
| -- Вспомогательная функция для проверки набора рецептов
| | local fruitImg = string.format( |
| local function checkRecipes(recipeIds)
| | '{{Предмет|%s|size=64px|vertical=1|imageTooltip=1|link=%s}}', |
| for _, recipeId in ipairs(recipeIds or {}) do | | prodId, seedName |
| local recipe = getRecipeById(recipeId)
| | ) |
| if recipe and recipe.result == targetResult then | | local seedImg = string.format( |
| return true
| | '{{Предмет|%s|size=64px|vertical=1|imageTooltip=1|l=|link=%s}}', |
| end | | seedId, seedName |
| end | | ) |
| return false
| | local plantImg = string.format( |
| end
| | '{{Предмет|%s-harvest|size=64px|l=|link=%s}}', |
| | seedId, seedName |
| | ) |
|
| |
|
| for _, lathe in ipairs(latheData) do | | local colGrowth = formatCharacteristics(seed) |
| local found = false | | local colConditions = formatConditions(seed) |
| if lathe.Lathe then | | local colHarvest = formatHarvestType(seed) |
| if checkRecipes(lathe.Lathe.staticRecipes) or checkRecipes(lathe.Lathe.dynamicRecipes) then
| | local colChemicals = formatChemicals(seed) |
| found = true
| | local colMutations = formatMutations(seed, data) |
| end
| |
| end
| |
| if not found and lathe.EmagLatheRecipes then
| |
| if checkRecipes(lathe.EmagLatheRecipes.emagStaticRecipes) or checkRecipes(lathe.EmagLatheRecipes.emagDynamicRecipes) then
| |
| found = true
| |
| end
| |
| end
| |
| if found and lathe.id then
| |
| table.insert(matchingLathes, lathe.id)
| |
| end
| |
| end
| |
|
| |
|
| if #matchingLathes == 0 then
| | local row = frame:preprocess(string.format( |
| return "Станок, производящий '" .. targetResult .. "', не найден." | | [[|- |
| | ! %s |
| | ! %s |
| | ! %s |
| | | %s |
| | | %s |
| | | %s |
| | | %s |
| | | %s ]], |
| | fruitImg, seedImg, plantImg, |
| | colGrowth, colConditions, colHarvest, |
| | colChemicals, colMutations |
| | )) |
| | table.insert(rows, row) |
| end | | end |
|
| |
|
| return "Найденные станки: " .. table.concat(matchingLathes, ", ") | | return generateHeader() .. table.concat(rows, '\n') .. '\n' .. generateFooter() |
| end | | end |
|
| |
|
| ---------------------------------------------------------------------
| |
| -- Основная функция модуля
| |
| -- Принимает первым аргументом режим обратного поиска:
| |
| -- reverseContained, reverseEquipment, reverseCargo, reverseLathe.
| |
| -- Второй (и последующие) аргументы передаются соответствующим функциям.
| |
| ---------------------------------------------------------------------
| |
| function p.main(frame) | | function p.main(frame) |
| local mode = frame.args[1] | | local args = frame.args |
| if not mode or mode == "" then | | local id = args[1] |
| return "Ошибка: не указан режим обратного поиска. Доступные режимы: reverseContained, reverseEquipment, reverseCargo, reverseLathe."
| | local mode = mw.text.trim(args[2] or ""):lower() |
| end
| | local seed = findSeedById(id, seedsData) |
| | if not seed then return "" end |
|
| |
|
| if mode == "reverseContained" then | | if mode == "growth" then |
| return p.reverseContained(frame) | | return formatCharacteristics(seed) |
| elseif mode == "reverseEquipment" then | | elseif mode == "conditions" then |
| return p.reverseEquipment(frame) | | return formatConditions(seed) |
| elseif mode == "reverseCargo" then | | elseif mode == "harvest" then |
| return p.reverseCargo(frame) | | return formatHarvestType(seed) |
| elseif mode == "reverseLathe" then | | elseif mode == "chemicals" then |
| return p.reverseLathe(frame) | | return formatChemicals(seed) |
| | elseif mode == "mutations" then |
| | return formatMutations(seed, seedsData) |
| else | | else |
| return "Неизвестный режим: " .. mode .. ". Доступные режимы: reverseContained, reverseEquipment, reverseCargo, reverseLathe." | | return "" |
| end | | end |
| end | | end |
|
| |
|
| return p | | return p |