Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local component = require("component")
- local computer = require("computer")
- local term = require("term")
- local serialization = require("serialization")
- -- Получаем все доступные мониторы и GPU
- local monitors = {}
- local gpus = {}
- -- Функция для поиска и настройки мониторов
- local function setupMonitors()
- -- Очищаем предыдущие списки
- monitors = {}
- gpus = {}
- -- Находим все экраны
- for address, componentType in component.list("screen") do
- local screen = component.proxy(address)
- table.insert(monitors, screen)
- end
- -- Находим GPU для каждого экрана
- for _, screen in ipairs(monitors) do
- -- Ищем свободный GPU
- local gpu = nil
- for gpuAddress, gpuType in component.list("gpu") do
- local currentGpu = component.proxy(gpuAddress)
- -- Проверяем, не занят ли GPU другим экраном
- local isFree = true
- for _, existingGpu in ipairs(gpus) do
- if existingGpu.address == currentGpu.address then
- isFree = false
- break
- end
- end
- -- Если GPU свободен, пробуем привязать к экрану
- if isFree then
- local success, err = pcall(function()
- currentGpu.bind(screen.address)
- end)
- if success then
- gpu = currentGpu
- break
- end
- end
- end
- -- Если GPU найден, добавляем его
- if gpu then
- -- Устанавливаем меньшее разрешение для увеличения текста
- local maxWidth, maxHeight = gpu.maxResolution()
- gpu.setResolution(math.floor(maxWidth / 2), math.floor(maxHeight / 2))
- table.insert(gpus, gpu)
- end
- end
- -- Если нет GPU, используем встроенный
- if #gpus == 0 then
- local defaultGpu = component.gpu
- local maxWidth, maxHeight = defaultGpu.maxResolution()
- defaultGpu.setResolution(math.floor(maxWidth / 2), math.floor(maxHeight / 2))
- table.insert(gpus, defaultGpu)
- end
- -- Логирование найденных мониторов и GPU
- print("Найдено мониторов: " .. #monitors)
- print("Найдено GPU: " .. #gpus)
- for i, gpu in ipairs(gpus) do
- print("GPU " .. i .. ": " .. tostring(gpu.address))
- end
- end
- -- Вызываем setup при инициализации
- setupMonitors()
- local radar = component.radar
- -- Константы
- local DATA_FILE = "player_data.txt"
- local UPDATE_INTERVAL = 1200 -- 20 минут в секундах
- local RADAR_RANGE = 64 -- максимальный радиус радара
- -- Структура данных для хранения информации об игроках
- local players = {}
- local lastUpdateTime = 0 -- Время последнего обновления
- -- Функция для загрузки данных из файла
- local function loadData()
- local file = io.open(DATA_FILE, "r")
- if file then
- local content = file:read("*all")
- file:close()
- local success, data = pcall(serialization.unserialize, content)
- if success and type(data) == "table" then
- players = {}
- for name, playerData in pairs(data) do
- if type(playerData) == "table" then
- players[name] = {
- status = playerData.status or "Вышел",
- totalTime = math.max(0, tonumber(playerData.totalTime) or 0),
- lastSeen = 0
- }
- end
- end
- end
- end
- end
- -- Функция для сохранения данных в файл
- local function saveData()
- local file = io.open(DATA_FILE, "w")
- if file then
- file:write(serialization.serialize(players))
- file:close()
- end
- end
- -- Функция обновления данных о игроках
- local function updatePlayers()
- local detected = radar.getPlayers()
- local currentTime = computer.uptime()
- -- Если это первый запуск или прошло много времени, сбрасываем lastUpdateTime
- if lastUpdateTime == 0 or currentTime - lastUpdateTime > 3600 then
- lastUpdateTime = currentTime
- end
- -- Вычисляем время между обновлениями
- local timeDelta = currentTime - lastUpdateTime
- -- Обновляем данные для обнаруженных игроков
- for _, player in ipairs(detected) do
- if not players[player.name] then
- players[player.name] = {
- status = "Здесь",
- totalTime = 0,
- lastSeen = currentTime
- }
- else
- players[player.name].status = "Здесь"
- -- Корректно обновляем общее время
- players[player.name].totalTime = math.max(0,
- (players[player.name].totalTime or 0) + timeDelta)
- players[player.name].lastSeen = currentTime
- end
- end
- -- Обновление статуса отсутствующих игроков
- for name, data in pairs(players) do
- local found = false
- for _, player in ipairs(detected) do
- if player.name == name then
- found = true
- break
- end
- end
- if not found then
- data.status = "Вышел"
- end
- end
- -- Обновляем время последнего обновления
- lastUpdateTime = currentTime
- saveData()
- end
- -- Функция форматирования времени
- local function formatTime(seconds)
- -- Ensure seconds is a number, default to 0 if not
- seconds = tonumber(seconds) or 0
- local hours = math.floor(seconds / 3600)
- local minutes = math.floor((seconds % 3600) / 60)
- local secs = math.floor(seconds % 60)
- return string.format("%02d:%02d:%02d", hours, minutes, secs)
- end
- -- Цветовая палитра
- local colors = {
- white = 0xFFFFFF, -- белый
- lime = 0x00FF00, -- лаймовый
- red = 0xFF0000, -- ярко-красный
- time = 0x87CEEB, -- цвет времени (светло-голубой)
- background = 0x000000 -- черный фон
- }
- -- Функция отрисовки интерфейса на всех мониторах
- local function drawInterface()
- -- Сортировка игроков
- local sortedPlayers = {}
- for name, data in pairs(players) do
- table.insert(sortedPlayers, {name = name, data = data})
- end
- table.sort(sortedPlayers, function(a, b)
- if a.data.status == b.data.status then
- return a.data.totalTime > b.data.totalTime
- end
- return a.data.status == "Здесь"
- end)
- -- Отрисовка на каждом мониторе
- for _, gpu in ipairs(gpus) do
- -- Получаем размеры монитора
- local w, h = gpu.getResolution()
- -- Устанавливаем цвета
- gpu.setBackground(colors.background)
- gpu.setForeground(colors.white)
- -- Очищаем экран
- gpu.fill(1, 1, w, h, " ")
- -- Рисуем декоративные линии
- gpu.fill(1, 1, w, 1, "=")
- gpu.fill(1, h, w, 1, "=")
- -- Отступы
- local leftMargin = 10
- local timeMargin = 30
- local rightMargin = 5
- -- Отображение топ-12 игроков
- for i = 1, math.min(12, #sortedPlayers) do
- local player = sortedPlayers[i]
- -- Ник игрока (слева с отступом)
- gpu.setForeground(colors.white)
- gpu.set(leftMargin, i + 2, player.name)
- -- Время (по центру)
- gpu.setForeground(colors.time)
- local timeText = formatTime(player.data.totalTime)
- gpu.set(leftMargin + timeMargin, i + 2, timeText)
- -- Статус (справа с отступом)
- if player.data.status == "Здесь" then
- gpu.setForeground(colors.lime)
- else
- gpu.setForeground(colors.red)
- end
- gpu.set(w - rightMargin - #player.data.status + 1, i + 2, player.data.status)
- end
- end
- end
- -- Главный цикл программы
- local function main()
- loadData()
- local lastUpdate = computer.uptime()
- while true do
- local currentTime = computer.uptime()
- -- Обновление данных
- updatePlayers()
- drawInterface()
- -- Проверка необходимости перезапуска
- if currentTime - lastUpdate >= UPDATE_INTERVAL then
- saveData()
- loadData()
- drawInterface()
- lastUpdate = computer.uptime()
- end
- os.sleep(1)
- end
- end
- -- Запуск программы
- main()
Advertisement
Add Comment
Please, Sign In to add comment