Advertisement
MoonlightOwl

Quantum Link Manager

Sep 19th, 2014
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 11.46 KB | None | 0 0
  1. -- Quantum Link Manager by Totoro --
  2. -- Version 2. All right reserved! --
  3.  
  4. local serial = require('serialization')
  5. local fs = require('filesystem')
  6. local event = require("event")
  7. local term = require('term')
  8. local com = require('component')
  9. local modem = com.modem
  10. local gpu = com.gpu
  11.  
  12. --    Colors   --
  13. backcolor = 0x000000
  14. forecolor = 0xFFFFFF
  15. infocolor = 0x0066FF
  16. errorcolor = 0xFF0000
  17. helpcolor = 0x00AA00
  18. inactivecolor = 0xCCCCCC
  19. goldcolor = 0xCCCC00
  20. --     ****     --
  21.  
  22. --     Codes    --
  23. pingcode = 0x031337
  24. refreshcode = 0xC0FFEE
  25. --     ****     --
  26.  
  27. -- == Variables == --
  28. local secret_port = 27
  29. local translate = true
  30. _, height = gpu.getResolution()
  31.  
  32. -- == Teleports List == --
  33. teleports = {}
  34.  
  35. function addTeleport(name, price, x, y, z)
  36.   table.insert(teleports, {name = name, price = price, x = x, y = y, z = z, blocked = false})
  37. end
  38. function changeTeleport(name, price, x, y, z)
  39.   for i=1, #teleports do
  40.     if teleports[i].name == name then
  41.       teleports[i].price = price
  42.       teleports[i].x = x
  43.       teleports[i].y = y
  44.       teleports[i].z = z
  45.       return true
  46.     end
  47.   end
  48.   return false
  49. end
  50. function blockTeleport(name, flag)
  51.   for i=1, #teleports do
  52.     if teleports[i].name == name then
  53.       teleports[i].blocked = flag
  54.       return true
  55.     end
  56.   end
  57.   return false
  58. end
  59.  
  60. function loadTeleports()
  61.   if fs.exists("telelist.txt") then
  62.     local file = io.open("telelist.txt", "r")
  63.     local data = file:read("*a")
  64.     teleports = serial.unserialize(data)
  65.     file:close()
  66.     if teleports == nil then teleports = {} end
  67.   end
  68. end
  69. function saveTeleports()
  70.   local file = io.open("telelist.txt", "w")
  71.   local data = serial.serialize(teleports)
  72.   file:write(data)
  73.   file:close()
  74. end
  75.  
  76. function refreshTable()
  77.   local data = serial.serialize(teleports)
  78.   for i=1, #users do
  79.     modem.send(users[i].address, secret_port, refreshcode, data)
  80.   end
  81.   infomessage("Новая таблица отправлена клиентам.\n")
  82. end
  83.  
  84.  
  85. -- == Users == ---
  86. users = {}
  87. superuser = nil
  88.  
  89. function addUser(address, desc)
  90.   table.insert(users, {address = address, description = desc})
  91. end
  92. function loadUsers()
  93.   if fs.exists("userlist.txt") then
  94.     local file = io.open("userlist.txt", "r")
  95.     local data = file:read("*a")
  96.     users = serial.unserialize(data)
  97.     file:close()
  98.     if users == nil then users = {} end
  99.   end
  100. end
  101. function saveUsers()
  102.   local file = io.open("userlist.txt", "w")
  103.   local data = serial.serialize(users)
  104.   file:write(data)
  105.   file:close()
  106. end
  107. function ping(address)
  108.   modem.send(address, secret_port, pingcode)
  109.   while true do
  110.     name, _, from, port, _, message = event.pull(10)
  111.     if name == 'key_down' then return false
  112.     elseif name == 'modem_message' then
  113.       if from == address and message == pingcode then
  114.         return true
  115.       else
  116.         return false
  117.       end
  118.     elseif name == nil then
  119.       errormessage('Тайм-аут запроса.\n')
  120.     end
  121.   end
  122. end
  123.  
  124.  
  125. -- == Terminal == --
  126. function yesno()
  127.   local name, _, _, code = event.pull(10, 'key_down')
  128.   if name ~= nil then
  129.     if code == 21 then
  130.       return true
  131.     end
  132.   end
  133.   return false
  134. end
  135.  
  136. function errormessage(text)
  137.   gpu.setForeground(errorcolor)
  138.   term.write(text)
  139.   gpu.setForeground(forecolor)
  140. end
  141. function infomessage(text)
  142.   gpu.setForeground(infocolor)
  143.   term.write(text)
  144.   gpu.setForeground(forecolor)
  145. end
  146. function userlist()
  147.   for i=1, #users do
  148.     term.write(users[i].address..': "'..users[i].description..'"\n')
  149.     if i > (height-2) then
  150.       infomessage("Нажмите любую кнопку, для продолжения.\n")
  151.       event.pull('key_down')
  152.     end
  153.   end
  154.   if #users == 0 then
  155.     print("Список пуст.")
  156.   end
  157. end
  158. function telelist()
  159.   for i=1, #teleports do
  160.     if teleports[i].blocked then gpu.setForeground(errorcolor) end
  161.     term.write(teleports[i].name..', $'..teleports[i].price..', [x='..teleports[i].x..' y='..teleports[i].y..' z='..teleports[i].z..']\n')
  162.     if teleports[i].blocked then gpu.setForeground(forecolor) end
  163.     if i > (height-2) then
  164.       infomessage("Нажмите любую кнопку, для продолжения.\n")
  165.       event.pull('key_down')
  166.     end
  167.   end
  168.   if #teleports == 0 then
  169.     print("Список пуст.")
  170.   end
  171. end
  172.  
  173. function getNewTeleport()
  174.   term.write("Название: ")
  175.   local name = string.sub(term.read(), 1, -2)
  176.   if name == '' then
  177.     errormessage("Пустое название.\n")
  178.     return false
  179.   end
  180.   term.write("Стоимость: ")
  181.   local price = tonumber(string.sub(term.read(), 1, -2))
  182.   if price < 0 then
  183.     errormessage("Телепорт не платит игроку.\n")
  184.     return false
  185.   end
  186.   term.write("Координаты через пробел: ")
  187.   local data = (string.sub(term.read(), 1, -2))
  188.   local loc = {}
  189.   n = 1
  190.   for i in string.gmatch(data, "%S+") do
  191.     loc[n] = tonumber(i)
  192.     n = n + 1
  193.   end
  194.   if loc[1] == nil or loc[2] == nil or loc[3] == nil then
  195.     errormessage("Неверно введены координаты.\n")
  196.     return false
  197.   end
  198.   addTeleport(name, price, loc[1], loc[2], loc[3])
  199.   infomessage("Новый телепорт в таблице.\n")
  200.   term.write("Обновить таблицу клиентам (y/n)? ")
  201.   if yesno() then
  202.     refreshTable()
  203.   end
  204. end
  205. function getNewUser()
  206.   term.write("Сетевой адрес: ")
  207.   local address = string.sub(term.read(addresshistory), 1, -2)
  208.   term.write("Проверка адреса... ")
  209.   if ping(address) then
  210.     term.write("Успешно.\n")
  211.  
  212.     term.write("Описание (можно опустить): ")
  213.     local desc = string.sub(term.read(), 1, -2)
  214.  
  215.     addUser(address, desc)
  216.     infomessage("Новый клиент добавлен в таблицу.\n")
  217.  
  218.     print("Послать новому клиенту таблицу? (y/n)")
  219.     if yesno() then
  220.       modem.send(address, secret_port, refreshcode, serial.serialize(teleports))
  221.       infomessage("Таблица отослана.\n")
  222.     else
  223.       errormessage("Отказ.\n")
  224.     end
  225.   else errormessage("Ошибка.\n") end
  226. end
  227.  
  228. function removeTeleport()
  229.   term.write("Название телепорта для удаления: ")
  230.   local name = string.sub(term.read(), 1, -2)
  231.  
  232.   for i=#teleports, 1, -1 do
  233.     if teleports[i].name == name then
  234.       table.remove(teleports, i)
  235.       infomessage("Телепорт '"..name.."' из таблицы удален.\n")
  236.       return true
  237.     end
  238.   end
  239.   errormessage("Телепорт '"..name.."' в таблице не найден.\n")
  240.   return false
  241. end
  242. function removeUser()
  243.   term.write("Адрес клиента для удаления (первые несколько символов): ")
  244.   local add = string.sub(term.read(), 1, -2)
  245.  
  246.   for i=#users, 1, -1 do
  247.     if string.sub(users[i].address, 1, #add) == add then
  248.       table.remove(users, i)
  249.       infomessage("Клиент '"..add.."' из таблицы удален.\n")
  250.       return true
  251.     end
  252.   end
  253.   errormessage("Клиент '"..add.."' в таблице не найден.\n")
  254.   return false
  255. end
  256.  
  257. helptext = {"[Quantum Link Manager by Totoro]\n",
  258. "Список доступных команд:\n",
  259. " add <user/teleport> - добавляет нового клиента, или запись в таблицу телепортов\n",
  260. " list <user/teleport> - показывает соответствующий список\n",
  261. " remove <user/teleport> - удаляет клиента или запись из таблицы телепортов\n",
  262. " refresh - рассылает таблицу клиентам\n",
  263. " block - блокирует телепорт в списке\n",
  264. " unblock - разблокирует телепорт в списке\n",
  265. " help - открывает справку\n",
  266. " quit - завершает программу\n"}
  267. function help()
  268.   gpu.setForeground(helpcolor)
  269.   for i=1, #helptext do
  270.     term.write(helptext[i], true)
  271.   end
  272.   gpu.setForeground(forecolor)
  273. end
  274.  
  275. function blockDialog(flag)
  276.   term.write("Введите название телепорта: ")
  277.   local name = string.sub(term.read(), 1, -2)
  278.   if blockTeleport(name, flag) then
  279.     if flag then
  280.       infomessage("Телепорт заблокирован.\n")
  281.     else
  282.       infomessage("Телепорт разблокирован.\n")
  283.     end
  284.     refreshTable()
  285.   else
  286.     errormessage("Телепорт с таким названием не найден.\n")
  287.   end
  288. end
  289.  
  290.  
  291.  
  292. history = {}
  293. addresshistory = {}
  294. loadTeleports()
  295. loadUsers()
  296.  
  297.  
  298. -- == Main == --
  299. modem.open(secret_port)
  300. term.clear()
  301. term.write(" [ Quantum Link Manager ]\n")
  302.  
  303. while true do
  304.   -- getting command
  305.   name, _, from, port, _, code, data = event.pull(1)
  306.  
  307.   if name == 'key_down' then
  308.     term.write(">> ")
  309.     command = string.sub(term.read(history), 1, -2)
  310.  
  311.     -- processing user input
  312.     if command == 'add' then                               -- variants
  313.       print("Возможные варианты: 'add user' или 'add teleport'")
  314.     elseif command == 'add teleport' then                  -- new teleport in table
  315.       getNewTeleport()
  316.     elseif command == 'add user' then                      -- new user in table
  317.       getNewUser()
  318.     elseif command == 'list' then                                                  -- variants =)
  319.       print("Возможные варианты: 'list user' или 'list teleport'")
  320.     elseif command == 'list user' or command == 'user list' then                   -- print list of users in table
  321.       userlist()
  322.     elseif command == 'list teleport' or command == 'teleport list' then           -- print list of teleports in table
  323.       telelist()
  324.     elseif command == 'remove' or command == 'delete' then -- variants
  325.       print("Возможные варианты: 'remove user' или 'remove teleport'")
  326.     elseif command == 'remove user' then                   -- remove user from table
  327.       removeUser()
  328.     elseif command == 'remove teleport' then               -- remove teleport from table
  329.       removeTeleport()
  330.     elseif command == 'refresh' then                       -- send new table to teleports
  331.       refreshTable()
  332.     elseif command == 'block' then                         -- block teleport
  333.       blockDialog(true)
  334.     elseif command == 'unblock' then                       -- ublock teleport
  335.       blockDialog(false)
  336.     elseif command == 'help' or command == '?' then        -- show help
  337.       help()
  338.     elseif command == 'exit' or command == 'quit' then     -- exit manager
  339.       break
  340.     else                                                   -- unknown command
  341.       errormessage("Неизвестная команда - '"..command.."'\n")
  342.     end
  343.   elseif name == 'modem_message' then
  344.     if code == refreshcode then
  345.       local t = serial.unserialize(data)
  346.       if t ~= nil then
  347.         teleports = t
  348.         infomessage("Получена новая таблица телепортов.\n")
  349.         if translate then refreshTable()
  350.         else
  351.           print("Разослать таблицу клиентам? (y/n)")
  352.           if yesno() then
  353.             refreshTable()
  354.           else
  355.             errormessage("Отказ.\n")
  356.           end
  357.         end
  358.       end
  359.     elseif code == pingcode then
  360.       modem.send(from, secret_port, pingcode)
  361.     end
  362.   end
  363. end
  364.  
  365.  
  366. -- == End == --
  367. saveTeleports()
  368. saveUsers()
  369. term.clear()
  370. modem.close(secret_port)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement