Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Quantum Link Manager by Totoro --
- -- Version 2. All right reserved! --
- local serial = require('serialization')
- local fs = require('filesystem')
- local event = require("event")
- local term = require('term')
- local com = require('component')
- local modem = com.modem
- local gpu = com.gpu
- -- Colors --
- backcolor = 0x000000
- forecolor = 0xFFFFFF
- infocolor = 0x0066FF
- errorcolor = 0xFF0000
- helpcolor = 0x00AA00
- inactivecolor = 0xCCCCCC
- goldcolor = 0xCCCC00
- -- **** --
- -- Codes --
- pingcode = 0x031337
- refreshcode = 0xC0FFEE
- -- **** --
- -- == Variables == --
- local secret_port = 27
- local translate = true
- _, height = gpu.getResolution()
- -- == Teleports List == --
- teleports = {}
- function addTeleport(name, price, x, y, z)
- table.insert(teleports, {name = name, price = price, x = x, y = y, z = z, blocked = false})
- end
- function changeTeleport(name, price, x, y, z)
- for i=1, #teleports do
- if teleports[i].name == name then
- teleports[i].price = price
- teleports[i].x = x
- teleports[i].y = y
- teleports[i].z = z
- return true
- end
- end
- return false
- end
- function blockTeleport(name, flag)
- for i=1, #teleports do
- if teleports[i].name == name then
- teleports[i].blocked = flag
- return true
- end
- end
- return false
- end
- function loadTeleports()
- if fs.exists("telelist.txt") then
- local file = io.open("telelist.txt", "r")
- local data = file:read("*a")
- teleports = serial.unserialize(data)
- file:close()
- if teleports == nil then teleports = {} end
- end
- end
- function saveTeleports()
- local file = io.open("telelist.txt", "w")
- local data = serial.serialize(teleports)
- file:write(data)
- file:close()
- end
- function refreshTable()
- local data = serial.serialize(teleports)
- for i=1, #users do
- modem.send(users[i].address, secret_port, refreshcode, data)
- end
- infomessage("Новая таблица отправлена клиентам.\n")
- end
- -- == Users == ---
- users = {}
- superuser = nil
- function addUser(address, desc)
- table.insert(users, {address = address, description = desc})
- end
- function loadUsers()
- if fs.exists("userlist.txt") then
- local file = io.open("userlist.txt", "r")
- local data = file:read("*a")
- users = serial.unserialize(data)
- file:close()
- if users == nil then users = {} end
- end
- end
- function saveUsers()
- local file = io.open("userlist.txt", "w")
- local data = serial.serialize(users)
- file:write(data)
- file:close()
- end
- function ping(address)
- modem.send(address, secret_port, pingcode)
- while true do
- name, _, from, port, _, message = event.pull(10)
- if name == 'key_down' then return false
- elseif name == 'modem_message' then
- if from == address and message == pingcode then
- return true
- else
- return false
- end
- elseif name == nil then
- errormessage('Тайм-аут запроса.\n')
- end
- end
- end
- -- == Terminal == --
- function yesno()
- local name, _, _, code = event.pull(10, 'key_down')
- if name ~= nil then
- if code == 21 then
- return true
- end
- end
- return false
- end
- function errormessage(text)
- gpu.setForeground(errorcolor)
- term.write(text)
- gpu.setForeground(forecolor)
- end
- function infomessage(text)
- gpu.setForeground(infocolor)
- term.write(text)
- gpu.setForeground(forecolor)
- end
- function userlist()
- for i=1, #users do
- term.write(users[i].address..': "'..users[i].description..'"\n')
- if i > (height-2) then
- infomessage("Нажмите любую кнопку, для продолжения.\n")
- event.pull('key_down')
- end
- end
- if #users == 0 then
- print("Список пуст.")
- end
- end
- function telelist()
- for i=1, #teleports do
- if teleports[i].blocked then gpu.setForeground(errorcolor) end
- term.write(teleports[i].name..', $'..teleports[i].price..', [x='..teleports[i].x..' y='..teleports[i].y..' z='..teleports[i].z..']\n')
- if teleports[i].blocked then gpu.setForeground(forecolor) end
- if i > (height-2) then
- infomessage("Нажмите любую кнопку, для продолжения.\n")
- event.pull('key_down')
- end
- end
- if #teleports == 0 then
- print("Список пуст.")
- end
- end
- function getNewTeleport()
- term.write("Название: ")
- local name = string.sub(term.read(), 1, -2)
- if name == '' then
- errormessage("Пустое название.\n")
- return false
- end
- term.write("Стоимость: ")
- local price = tonumber(string.sub(term.read(), 1, -2))
- if price < 0 then
- errormessage("Телепорт не платит игроку.\n")
- return false
- end
- term.write("Координаты через пробел: ")
- local data = (string.sub(term.read(), 1, -2))
- local loc = {}
- n = 1
- for i in string.gmatch(data, "%S+") do
- loc[n] = tonumber(i)
- n = n + 1
- end
- if loc[1] == nil or loc[2] == nil or loc[3] == nil then
- errormessage("Неверно введены координаты.\n")
- return false
- end
- addTeleport(name, price, loc[1], loc[2], loc[3])
- infomessage("Новый телепорт в таблице.\n")
- term.write("Обновить таблицу клиентам (y/n)? ")
- if yesno() then
- refreshTable()
- end
- end
- function getNewUser()
- term.write("Сетевой адрес: ")
- local address = string.sub(term.read(addresshistory), 1, -2)
- term.write("Проверка адреса... ")
- if ping(address) then
- term.write("Успешно.\n")
- term.write("Описание (можно опустить): ")
- local desc = string.sub(term.read(), 1, -2)
- addUser(address, desc)
- infomessage("Новый клиент добавлен в таблицу.\n")
- print("Послать новому клиенту таблицу? (y/n)")
- if yesno() then
- modem.send(address, secret_port, refreshcode, serial.serialize(teleports))
- infomessage("Таблица отослана.\n")
- else
- errormessage("Отказ.\n")
- end
- else errormessage("Ошибка.\n") end
- end
- function removeTeleport()
- term.write("Название телепорта для удаления: ")
- local name = string.sub(term.read(), 1, -2)
- for i=#teleports, 1, -1 do
- if teleports[i].name == name then
- table.remove(teleports, i)
- infomessage("Телепорт '"..name.."' из таблицы удален.\n")
- return true
- end
- end
- errormessage("Телепорт '"..name.."' в таблице не найден.\n")
- return false
- end
- function removeUser()
- term.write("Адрес клиента для удаления (первые несколько символов): ")
- local add = string.sub(term.read(), 1, -2)
- for i=#users, 1, -1 do
- if string.sub(users[i].address, 1, #add) == add then
- table.remove(users, i)
- infomessage("Клиент '"..add.."' из таблицы удален.\n")
- return true
- end
- end
- errormessage("Клиент '"..add.."' в таблице не найден.\n")
- return false
- end
- helptext = {"[Quantum Link Manager by Totoro]\n",
- "Список доступных команд:\n",
- " add <user/teleport> - добавляет нового клиента, или запись в таблицу телепортов\n",
- " list <user/teleport> - показывает соответствующий список\n",
- " remove <user/teleport> - удаляет клиента или запись из таблицы телепортов\n",
- " refresh - рассылает таблицу клиентам\n",
- " block - блокирует телепорт в списке\n",
- " unblock - разблокирует телепорт в списке\n",
- " help - открывает справку\n",
- " quit - завершает программу\n"}
- function help()
- gpu.setForeground(helpcolor)
- for i=1, #helptext do
- term.write(helptext[i], true)
- end
- gpu.setForeground(forecolor)
- end
- function blockDialog(flag)
- term.write("Введите название телепорта: ")
- local name = string.sub(term.read(), 1, -2)
- if blockTeleport(name, flag) then
- if flag then
- infomessage("Телепорт заблокирован.\n")
- else
- infomessage("Телепорт разблокирован.\n")
- end
- refreshTable()
- else
- errormessage("Телепорт с таким названием не найден.\n")
- end
- end
- history = {}
- addresshistory = {}
- loadTeleports()
- loadUsers()
- -- == Main == --
- modem.open(secret_port)
- term.clear()
- term.write(" [ Quantum Link Manager ]\n")
- while true do
- -- getting command
- name, _, from, port, _, code, data = event.pull(1)
- if name == 'key_down' then
- term.write(">> ")
- command = string.sub(term.read(history), 1, -2)
- -- processing user input
- if command == 'add' then -- variants
- print("Возможные варианты: 'add user' или 'add teleport'")
- elseif command == 'add teleport' then -- new teleport in table
- getNewTeleport()
- elseif command == 'add user' then -- new user in table
- getNewUser()
- elseif command == 'list' then -- variants =)
- print("Возможные варианты: 'list user' или 'list teleport'")
- elseif command == 'list user' or command == 'user list' then -- print list of users in table
- userlist()
- elseif command == 'list teleport' or command == 'teleport list' then -- print list of teleports in table
- telelist()
- elseif command == 'remove' or command == 'delete' then -- variants
- print("Возможные варианты: 'remove user' или 'remove teleport'")
- elseif command == 'remove user' then -- remove user from table
- removeUser()
- elseif command == 'remove teleport' then -- remove teleport from table
- removeTeleport()
- elseif command == 'refresh' then -- send new table to teleports
- refreshTable()
- elseif command == 'block' then -- block teleport
- blockDialog(true)
- elseif command == 'unblock' then -- ublock teleport
- blockDialog(false)
- elseif command == 'help' or command == '?' then -- show help
- help()
- elseif command == 'exit' or command == 'quit' then -- exit manager
- break
- else -- unknown command
- errormessage("Неизвестная команда - '"..command.."'\n")
- end
- elseif name == 'modem_message' then
- if code == refreshcode then
- local t = serial.unserialize(data)
- if t ~= nil then
- teleports = t
- infomessage("Получена новая таблица телепортов.\n")
- if translate then refreshTable()
- else
- print("Разослать таблицу клиентам? (y/n)")
- if yesno() then
- refreshTable()
- else
- errormessage("Отказ.\n")
- end
- end
- end
- elseif code == pingcode then
- modem.send(from, secret_port, pingcode)
- end
- end
- end
- -- == End == --
- saveTeleports()
- saveUsers()
- term.clear()
- modem.close(secret_port)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement