FeyMen

10

Dec 31st, 2024 (edited)
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 9.46 KB | None | 0 0
  1. local component = require("component")
  2. local computer = require("computer")
  3. local term = require("term")
  4. local serialization = require("serialization")
  5.  
  6. -- Получаем все доступные мониторы и GPU
  7. local monitors = {}
  8. local gpus = {}
  9.  
  10. -- Функция для поиска и настройки мониторов
  11. local function setupMonitors()
  12.     -- Очищаем предыдущие списки
  13.     monitors = {}
  14.     gpus = {}
  15.  
  16.     -- Находим все экраны
  17.     for address, componentType in component.list("screen") do
  18.         local screen = component.proxy(address)
  19.         table.insert(monitors, screen)
  20.     end
  21.  
  22.     -- Находим GPU для каждого экрана
  23.     for _, screen in ipairs(monitors) do
  24.         -- Ищем свободный GPU
  25.         local gpu = nil
  26.         for gpuAddress, gpuType in component.list("gpu") do
  27.             local currentGpu = component.proxy(gpuAddress)
  28.  
  29.             -- Проверяем, не занят ли GPU другим экраном
  30.             local isFree = true
  31.             for _, existingGpu in ipairs(gpus) do
  32.                 if existingGpu.address == currentGpu.address then
  33.                     isFree = false
  34.                     break
  35.                 end
  36.             end
  37.  
  38.             -- Если GPU свободен, пробуем привязать к экрану
  39.             if isFree then
  40.                 local success, err = pcall(function()
  41.                     currentGpu.bind(screen.address)
  42.                 end)
  43.  
  44.                 if success then
  45.                     gpu = currentGpu
  46.                     break
  47.                 end
  48.             end
  49.         end
  50.  
  51.         -- Если GPU найден, добавляем его
  52.         if gpu then
  53.             -- Устанавливаем меньшее разрешение для увеличения текста
  54.             local maxWidth, maxHeight = gpu.maxResolution()
  55.             gpu.setResolution(math.floor(maxWidth / 2), math.floor(maxHeight / 2))
  56.             table.insert(gpus, gpu)
  57.         end
  58.     end
  59.  
  60.     -- Если нет GPU, используем встроенный
  61.     if #gpus == 0 then
  62.         local defaultGpu = component.gpu
  63.         local maxWidth, maxHeight = defaultGpu.maxResolution()
  64.         defaultGpu.setResolution(math.floor(maxWidth / 2), math.floor(maxHeight / 2))
  65.         table.insert(gpus, defaultGpu)
  66.     end
  67.  
  68.     -- Логирование найденных мониторов и GPU
  69.     print("Найдено мониторов: " .. #monitors)
  70.     print("Найдено GPU: " .. #gpus)
  71.     for i, gpu in ipairs(gpus) do
  72.         print("GPU " .. i .. ": " .. tostring(gpu.address))
  73.     end
  74. end
  75.  
  76. -- Вызываем setup при инициализации
  77. setupMonitors()
  78.  
  79. local radar = component.radar
  80.  
  81. -- Константы
  82. local DATA_FILE = "player_data.txt"
  83. local UPDATE_INTERVAL = 1200 -- 20 минут в секундах
  84. local RADAR_RANGE = 64 -- максимальный радиус радара
  85.  
  86. -- Структура данных для хранения информации об игроках
  87. local players = {}
  88. local lastUpdateTime = 0  -- Время последнего обновления
  89.  
  90. -- Функция для загрузки данных из файла
  91. local function loadData()
  92.     local file = io.open(DATA_FILE, "r")
  93.     if file then
  94.         local content = file:read("*all")
  95.         file:close()
  96.         local success, data = pcall(serialization.unserialize, content)
  97.         if success and type(data) == "table" then
  98.             players = {}
  99.             for name, playerData in pairs(data) do
  100.                 if type(playerData) == "table" then
  101.                     players[name] = {
  102.                         status = playerData.status or "Вышел",
  103.                         totalTime = math.max(0, tonumber(playerData.totalTime) or 0),
  104.                         lastSeen = 0
  105.                     }
  106.                 end
  107.             end
  108.         end
  109.     end
  110. end
  111.  
  112. -- Функция для сохранения данных в файл
  113. local function saveData()
  114.     local file = io.open(DATA_FILE, "w")
  115.     if file then
  116.         file:write(serialization.serialize(players))
  117.         file:close()
  118.     end
  119. end
  120.  
  121. -- Функция обновления данных о игроках
  122. local function updatePlayers()
  123.     local detected = radar.getPlayers()
  124.     local currentTime = computer.uptime()
  125.  
  126.     -- Если это первый запуск или прошло много времени, сбрасываем lastUpdateTime
  127.     if lastUpdateTime == 0 or currentTime - lastUpdateTime > 3600 then
  128.         lastUpdateTime = currentTime
  129.     end
  130.  
  131.     -- Вычисляем время между обновлениями
  132.     local timeDelta = currentTime - lastUpdateTime
  133.  
  134.     -- Обновляем данные для обнаруженных игроков
  135.     for _, player in ipairs(detected) do
  136.         if not players[player.name] then
  137.             players[player.name] = {
  138.                 status = "Здесь",
  139.                 totalTime = 0,
  140.                 lastSeen = currentTime
  141.             }
  142.         else
  143.             players[player.name].status = "Здесь"
  144.             -- Корректно обновляем общее время
  145.             players[player.name].totalTime = math.max(0,
  146.                 (players[player.name].totalTime or 0) + timeDelta)
  147.             players[player.name].lastSeen = currentTime
  148.         end
  149.     end
  150.  
  151.     -- Обновление статуса отсутствующих игроков
  152.     for name, data in pairs(players) do
  153.         local found = false
  154.         for _, player in ipairs(detected) do
  155.             if player.name == name then
  156.                 found = true
  157.                 break
  158.             end
  159.         end
  160.         if not found then
  161.             data.status = "Вышел"
  162.         end
  163.     end
  164.  
  165.     -- Обновляем время последнего обновления
  166.     lastUpdateTime = currentTime
  167.  
  168.     saveData()
  169. end
  170.  
  171. -- Функция форматирования времени
  172. local function formatTime(seconds)
  173.     -- Ensure seconds is a number, default to 0 if not
  174.     seconds = tonumber(seconds) or 0
  175.     local hours = math.floor(seconds / 3600)
  176.     local minutes = math.floor((seconds % 3600) / 60)
  177.     local secs = math.floor(seconds % 60)
  178.     return string.format("%02d:%02d:%02d", hours, minutes, secs)
  179. end
  180.  
  181. -- Цветовая палитра
  182. local colors = {
  183.     white = 0xFFFFFF,     -- белый
  184.     lime = 0x00FF00,      -- лаймовый
  185.     red = 0xFF0000,       -- ярко-красный
  186.     time = 0x87CEEB,      -- цвет времени (светло-голубой)
  187.     background = 0x000000 -- черный фон
  188. }
  189.  
  190. -- Функция отрисовки интерфейса на всех мониторах
  191. local function drawInterface()
  192.     -- Сортировка игроков
  193.     local sortedPlayers = {}
  194.     for name, data in pairs(players) do
  195.         table.insert(sortedPlayers, {name = name, data = data})
  196.     end
  197.  
  198.     table.sort(sortedPlayers, function(a, b)
  199.         if a.data.status == b.data.status then
  200.             return a.data.totalTime > b.data.totalTime
  201.         end
  202.         return a.data.status == "Здесь"
  203.     end)
  204.  
  205.     -- Отрисовка на каждом мониторе
  206.     for _, gpu in ipairs(gpus) do
  207.         -- Получаем размеры монитора
  208.         local w, h = gpu.getResolution()
  209.  
  210.         -- Устанавливаем цвета
  211.         gpu.setBackground(colors.background)
  212.         gpu.setForeground(colors.white)
  213.  
  214.         -- Очищаем экран
  215.         gpu.fill(1, 1, w, h, " ")
  216.  
  217.         -- Рисуем декоративные линии
  218.         gpu.fill(1, 1, w, 1, "=")
  219.         gpu.fill(1, h, w, 1, "=")
  220.  
  221.         -- Отступы
  222.         local leftMargin = 10
  223.         local timeMargin = 30
  224.         local rightMargin = 5
  225.  
  226.         -- Отображение топ-12 игроков
  227.         for i = 1, math.min(12, #sortedPlayers) do
  228.             local player = sortedPlayers[i]
  229.  
  230.             -- Ник игрока (слева с отступом)
  231.             gpu.setForeground(colors.white)
  232.             gpu.set(leftMargin, i + 2, player.name)
  233.  
  234.             -- Время (по центру)
  235.             gpu.setForeground(colors.time)
  236.             local timeText = formatTime(player.data.totalTime)
  237.             gpu.set(leftMargin + timeMargin, i + 2, timeText)
  238.  
  239.             -- Статус (справа с отступом)
  240.             if player.data.status == "Здесь" then
  241.                 gpu.setForeground(colors.lime)
  242.             else
  243.                 gpu.setForeground(colors.red)
  244.             end
  245.             gpu.set(w - rightMargin - #player.data.status + 1, i + 2, player.data.status)
  246.         end
  247.     end
  248. end
  249.  
  250. -- Главный цикл программы
  251. local function main()
  252.     loadData()
  253.     local lastUpdate = computer.uptime()
  254.  
  255.     while true do
  256.         local currentTime = computer.uptime()
  257.  
  258.         -- Обновление данных
  259.         updatePlayers()
  260.         drawInterface()
  261.  
  262.         -- Проверка необходимости перезапуска
  263.         if currentTime - lastUpdate >= UPDATE_INTERVAL then
  264.             saveData()
  265.             loadData()
  266.             drawInterface()
  267.             lastUpdate = computer.uptime()
  268.         end
  269.  
  270.         os.sleep(1)
  271.     end
  272. end
  273.  
  274. -- Запуск программы
  275. main()
  276.  
Advertisement
Add Comment
Please, Sign In to add comment