Модуль:Prototypes/Механика/Исследование
Материал из Space Station 14 Вики
Версия от 08:37, 9 октября 2024; Pok (обсуждение | вклад)
Для документации этого модуля может быть создана страница Модуль:Prototypes/Механика/Исследование/doc
local p = {}
-- Таблица для иконок исследований в зависимости от их ID
local iconMapping = {
-- CivilianServices
["Hydroponics"] = "SeedExtractor",
["CritterMechs"] = "MechHamtr",
["AudioVisualCommunication"] = "SurveillanceCameraConstructed",
["AdvancedEntertainment"] = "ComputerTelevision",
["RoboticCleanliness"] = "BorgChassisJanitor",
["FauxAstroTiles"] = "FauxTileAstroIce",
["MeatManipulation"] = "FatExtractor",
["BiochemicalStasis"] = "StasisBed",
["MechanizedTreatment"] = "BorgChassisMedical",
["AdvancedCleaning"] = "AdvMopItem",
["HONKMech"] = "MechHonker",
["AdvancedSpray"] = "WeaponSprayNozzle",
["BluespaceCargoTransport"] = "CargoTelepad",
["QuantumFiberWeaving"] = "ClothingShoesBootsSpeed",
["BluespaceChemistry"] = "BluespaceBeaker",
-- Arsenal
["SalvageWeapons"] = "WeaponProtoKineticAccelerator",
["DraconicMunitions"] = "MagazineBoxPistolIncendiary",
["WeaponizedLaserManipulation"] = "WeaponLaserCarbine",
["NonlethalAmmunition"] = "ShellShotgunBeanbag",
["UraniumMunitions"] = "SheetUranium1",
["AdvancedRiotControl"] = "Truncheon",
["ExplosiveTechnology"] = "ExplosivePayload",
["SpecialMeans"] = "ClothingBackpackElectropack",
["ConcentratedLaserWeaponry"] = "WeaponLaserCannon",
["WaveParticleHarnessing"] = "WeaponXrayCannon",
["BasicShuttleArmament"] = "PowerCageRecharger",
["PortableMicrofusionWeaponry"] = "WeaponAdvancedLaser",
["ExperimentalBatteryAmmo"] = "WeaponLaserSvalinn",
["AdvancedShuttleWeapon"] = "MagazineGrenadeEmpty",
["BasicRobotics"] = "ExosuitFabricator",
-- Experimental
["BasicRobotics"] = "ExosuitFabricator",
["BasicAnomalousResearch"] = "AnomalyScanner",
["BasicXenoArcheology"] = "MachineArtifactAnalyzer",
["AlternativeResearch"] = "ComputerTechnologyDiskTerminal",
["MagnetsTech"] = "ClothingShoesBootsMagSci",
["AnomalyCoreHarnessing"] = "WeaponGauntletGorilla",
["AbnormalArtifactManipulation"] = "MachineArtifactCrusher",
["AdvancedAnomalyResearch"] = "MachineAnomalySynchronizer",
["DeterrenceTechnologies"] = "WeaponParticleDecelerator",
["GravityManipulation"] = "WeaponForceGun",
["QuantumLeaping"] = "DeviceQuantumSpinInverter",
-- Industrial
["SalvageEquipment"] = "MiningDrill",
["SpaceScanning"] = "HandHeldMassScanner",
["AdvancedPowercells"] = "TurboItemRecharger",
["MechanicalCompression"] = "MachineFlatpacker",
["IndustrialEngineering"] = "AutolatheHyperConvection",
["PowerGeneration"] = "PortableGeneratorPacman",
["AtmosphericTech"] = "GasThermoMachineFreezer",
["RipleyAPLU"] = "MechRipley",
["Shuttlecraft"] = "Gyroscope",
["AdvancedAtmospherics"] = "GasThermoMachineHellfireFreezer",
["AdvancedToolsTechnology"] = "WelderExperimental",
["MassExcavation"] = "MiningDrillDiamond",
["BluespaceStorage"] = "ClothingBackpackHolding",
["PortableFission"] = "PowerCellMicroreactor",
}
-- Функция для перевода ID плат в ID машин
local function translateBoardIDToMachineID(boardID)
-- Загрузка данных из JSON
local data = mw.text.jsonDecode(mw.title.new("Участник:IanComradeBot/entity_prototypes.json"):getContent())
-- Поиск платы по ID и извлечение её названия
local board = data[boardID]
if not board or not board.name then
return nil -- Если платы нет в данных, возвращаем nil
end
-- Проверка наличия "(машинная плата)" или "(консольная плата)" в имени
if not board.name:find("%(машинная плата%)") and not board.name:find("%(консольная плата%)") then
return nil -- Если в имени нет одной из фраз, возвращаем nil
end
-- Удаление "(машинная плата)" и "(консольная плата)" из имени платы
local machineName = board.name:gsub(" %(машинная плата%)", ""):gsub(" %(консольная плата%)", "")
-- Список исключений
local excludeWords = {"Unanchored", "Debug", "Admin"}
-- Поиск машины по новому названию
for _, entity in pairs(data) do
if entity.name == machineName then
-- Проверка на наличие исключений в ID
local shouldExclude = false
for _, word in ipairs(excludeWords) do
if entity.id:find(word) then
shouldExclude = true
break
end
end
if not shouldExclude then
return entity.id -- Возвращаем ID машины
end
end
end
return nil -- Если машина не найдена, возвращаем nil
end
function p.main(frame)
-- Подключение CSS файла
local cssLink = frame:extensionTag('templatestyles', '', {
src = 'Шаблон:Research/styles.css'
})
local discipline = frame.args.discipline or ""
-- Названия технологий
local disciplineName = ({
Arsenal = "Арсенал",
Industrial = "Промышленность",
Experimental = "Экспериментальное",
CivilianServices = "Обслуживание персонала"
})[discipline]
-- Загрузка данных из JSON
local data = mw.text.jsonDecode(mw.title.new("User:IanComradeBot/research prototypes.json"):getContent())
local out = cssLink
local found = false -- Флаг для отслеживания наличия элементов
-- Обработка данных
if data[discipline] then -- Проверяем, существует ли ключ для discipline
for _, tech in ipairs(data[discipline]) do
found = true
-- Цвета для номеров уровней
local tierColor = ({
[1] = "#54d554", -- зеленый
[2] = "#ed9000", -- оранжевый
[3] = "#d72a2a" -- красный
})[tech.tier]
-- Формирование HTML для каждой технологии
out = out .. '<div class="research" id="' .. discipline .. '">'
local iconId = iconMapping[tech.id] or tech.id -- Получаем iconId на основе tech.id
out = out .. '<div class="research__images">[[Файл:' .. iconId .. '.png|64x64px|центр|link=]]</div>'
out = out .. '<div class="research__name">' .. tech.name .. '[[Файл:' .. discipline .. '.png|16px|link=]]</div>'
out = out .. '<div class="research__type">'
out = out .. '<div>Уровень: <span style="color:' .. tierColor .. ';">' .. tech.tier .. '</span></div>'
out = out .. '<div class="research__technology">' .. disciplineName .. '</div>'
out = out .. '<div>Стоимость: <span style="color:#DA70D6;">' .. tech.cost .. '</span></div>'
out = out .. '</div>'
out = out .. '<div class="research__unblocks">Разблокирует:'
out = out .. '<ul>'
-- Проверка каждого ID в recipeUnlocks
for _, recipe in ipairs(tech.recipeUnlocks) do
local machineID = translateBoardIDToMachineID(recipe) or recipe -- Переводим только платы, остальные оставляем как есть
out = out .. frame:preprocess('<li>{{#invoke:Entity Lookup|createimagetooltip|Файл:' .. machineID .. '.png|' .. machineID .. '|Мета=32x32px,link=}} {{#invoke:Entity Lookup|getname|' .. machineID .. '}}</li>')
end
out = out .. '</ul>'
out = out .. '</div>'
out = out .. '</div>'
end
end
if not found then
out = out .. '<div>Нет доступных технологий.</div>'
end
return out
end
return p