Advertisement
Asioron

SG

Jan 4th, 2017
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 34.70 KB | None | 0 0
  1.  ----------------------------------------------------
  2.  --                    Программа                   --
  3.  --       для управления вратами из мода SG        --
  4.  --       в игре Minecraft с модом OpenComputers   --
  5.  --          проект http://computercraft.ru        --
  6.  --                 2017, © Asior                  --
  7.  ----------------------------------------------------
  8. -- Version 0.01
  9. local com = require("computer")
  10. local gpu =  require("component").gpu
  11. local event = require("event")
  12. local term = require("term")
  13. local unicode = require("unicode")
  14. local stargate = require("component").stargate
  15. local serialization = require("serialization")
  16. local fl = require("filesystem")
  17.  
  18. local function PrintLine(x1, y1, x2, y2, sms, vertical, colorBr, colorLet) -- быстрая отрисовка рамок
  19.   local vr = ''
  20.   if not vertical then vertical = false end
  21.   if not x2 then x2 = x1 end
  22.   if not y2 then y2 = y1 end
  23.   if not colorBr then gpu.setBackground(0x000000) else gpu.setBackground(colorBr) end
  24.   if not colorLet then gpu.setForeground(0xffffff) else gpu.setForeground(colorLet) end
  25.   if not vertical then -- если нарисовать горизонтальную строку
  26.     vr = (sms):rep(x2 - x1 + 1)
  27.   else -- если нарисовать вертикальную строку
  28.     vr = (sms):rep(y2 - y1 + 1)
  29.   end
  30.   gpu.set(x1, y1, vr, vertical)
  31.   gpu.setBackground(0x000000)
  32.   gpu.setForeground(0xffffff)
  33. end
  34.  
  35. local function frame() -- рамка, а что ж еще
  36.   local h, w = 19, 54
  37.   PrintLine(1, 1, nil, nil, '╔')
  38.   PrintLine(w, 1, nil, nil, '╗')
  39.   PrintLine(1, 19, nil, nil, '╚')
  40.   PrintLine(w, 19, nil, nil, '╝')
  41.   PrintLine(2, 1, w - 1, nil, '═')
  42.   PrintLine(1, 2, nil, 18, '║', true)
  43.   PrintLine(w, 2, nil, 18, '║', true)
  44.   PrintLine(2, 19, w - 1, nil, '═')
  45.  
  46.   PrintLine(30, 4, nil, 18, '║', true)
  47.   PrintLine(30, 19, nil, nil, '╩', false)
  48.  
  49.   PrintLine(1, 3, nil, nil, '╠')
  50.   PrintLine(2, 3, w - 1, nil, '═')
  51.   PrintLine(30, 3, nil, nil, '╦', false)
  52.   PrintLine(w, 3, nil, nil, '╣')
  53. end
  54.  
  55. local function ScreenBuffer(x1, y1, x2, y2, save) -- Буфер экрана. Вырезает кусок экрана, потом возвращает
  56.   if save then
  57.     Buffer = {}
  58.     for i = y1, y2 do
  59.       for i1 = x1, x2 do
  60.         local s, b, f = gpu.get(i1, i)
  61.         Buffer[i..i1] = {['s'] = s, ['b'] = b, ['f'] = f}
  62.       end
  63.     end
  64.   else
  65.     for i = y1, y2 do
  66.       for i1 = x1, x2 do
  67.         gpu.setBackground(Buffer[i..i1].f)
  68.         gpu.setForeground(Buffer[i..i1].b)
  69.         gpu.set(i1, i, Buffer[i..i1].s)
  70.       end
  71.     end
  72.     Buffer = {}
  73.     gpu.setBackground(0x000000)
  74.     gpu.setForeground(0xffffff)
  75.   end
  76. end
  77.  
  78. local function errors(x, y, sms, color, time, scr, name) -- окно ошибок -- координаты по х, у;сообщение;цвет;время показа; не запоминать?
  79.   local h, w = #sms + 3, 32
  80.   if not scr then ScreenBuffer(x, y, x + w, y + h, true) end
  81.   PrintLine(x, y, nil, nil, '╔')
  82.   PrintLine(x + w, y, nil, nil, '╗')
  83.   PrintLine(x, y + h, nil, nil, '╚')
  84.   PrintLine(x + w, y + h, nil, nil, '╝')
  85.   PrintLine(x + 1, y, x + w - 1, nil, '═')
  86.   PrintLine(x, y + 1, nil, y + h - 1, '║', true)
  87.   PrintLine(x + w, y + 1, nil, y + h - 1, '║', true)
  88.   PrintLine(x + 1, y + h, x + w - 1, nil, '═')
  89.   gpu.setBackground(color)
  90.   gpu.fill(x + 1, y + 1, w - 1, h - 1, ' ')
  91.   gpu.set(math.floor(x + w/2 - unicode.len(sms[1])/2), y + 1, sms[1])
  92.   for i = 2, #sms do
  93.     gpu.set(x + 2, y + i + 1, sms[i])
  94.   end
  95.   gpu.setBackground(0x000000)
  96.   os.sleep(0.5)
  97.   local t, _, _, _, k = event.pull(time)
  98.   if t == 'touch' and k == 1 and name == Temp[2].name1 then
  99.     t = true
  100.   else
  101.     t = false
  102.   end
  103.   if not scr then ScreenBuffer(x, y, x + w, y + h, false) end
  104.   return t
  105. end
  106.  
  107. local function bazaAdress(repetition, append, score, random) -- случайная база данных (рандом)
  108.   -- удаление; дозапись; подсчет базы адресов; случайный адрес
  109.   local files = "../Stargate/System/Baza_Adress.csv"  
  110.   if repetition then
  111.     fl.remove(files)
  112.   end
  113.   file = io.open(files, 'r')
  114.   if file  ~=  nil then
  115.     if append then
  116.       file:close()
  117.       file = io.open(files, 'a')
  118.       if #AllBaza>0 then
  119.         for i = 1, #AllBaza do
  120.           file:write(tostring(AllBaza[i])..';\n')
  121.         end
  122.       else
  123.         errors(13, 7, {'Нечем заполнять'}, 0x00aa00, 1, false)
  124.       end
  125.       file:close()
  126.     elseif score then
  127.       local i, a = 0, ''
  128.       repeat
  129.         i = i + 1
  130.         a = file:read()
  131.         -- print(i..'|'..tostring(a))
  132.       until a == nil
  133.       file:close()
  134.       AllBaza.num = i - 1
  135.       return
  136.     elseif random then
  137.       local a = math.random(AllBaza.num) + 1
  138.       local i, vr = 0, ''
  139.       repeat
  140.         i = i + 1
  141.         vr = file:read()
  142.       until i == a
  143.       file:close()
  144.       return vr
  145.     end
  146.   else
  147.     file = io.open(files, 'w')
  148.     if #AllBaza>0 then
  149.       for i = 1, #AllBaza do
  150.         file:write(tostring(AllBaza[i])..';\n')
  151.       end
  152.     else
  153.       errors(13, 7, {'Нечем заполнять'}, 0x00aa00, 1, false)
  154.     end
  155.     file:close()
  156.   end
  157. end
  158.  
  159. local function usersQuantity(save) -- статистика пользователей (костыль, хз как считать кол - во файлов)
  160.   if save then
  161.     file = io.open("../Stargate/Users/Stat.csv", 'w')
  162.     file:write(usersNum + 1)
  163.   else
  164.     file = io.open("../Stargate/Users/Stat.csv", 'r')
  165.     if file == nil then
  166.       usersNum = 0
  167.       usersQuantity(true)
  168.       return
  169.     else
  170.       usersNum = tonumber(file:read())
  171.     end
  172.   end
  173.   file:close()
  174. end
  175.  
  176. local function appendFile(files) -- перезапись файла пользователя
  177.   local vr, a = {}, nil
  178.   file = io.open(files, 'w')
  179.   for i = 1, #UserBaza do
  180.     file:write(tostring(UserBaza[i].name)..';'..tostring(UserBaza[i].adress)..';\n')
  181.   end
  182.   file:write(tostring(UserBaza[1].ends)..';Последний;\n')
  183.   file:close()
  184. end
  185.  
  186. local function toboolean(string) -- конвертор из строки в булевый
  187.   return string == "true"
  188. end
  189.  
  190. local function openFile(files, numBaza, repetition, append) -- имя файла(ник); номер базы (1 - 3); удаление; дозапись; подсчет базы адресов; случайный адрес -- загрузка или перезапись настроек в файл
  191.   local file = nil
  192.  -- задаем адрес файла
  193.   if numBaza == 2 then -- имя;адрес;
  194.     files = "../Stargate/Users/"..files.."__Baza.csv"
  195.   elseif numBaza == 3 then -- имя;адрес;доступ;
  196.     files = "../Stargate/System/Baza.csv"
  197.   end
  198.  -- проверка на удаление
  199.   if repetition then
  200.     fl.remove(files)
  201.   end
  202.   if append then
  203.     appendFile(files)
  204.     return
  205.   end
  206.   file = io.open(files, "r")
  207.   if file == nil then -- если новый пользователь
  208.     file = io.open(files, "w")
  209.     if numBaza == 2 then
  210.       errors(13, 7, {'Привет новичкам!', "Пожалуйста, подождите, идет", "создание вашего идентификатора"}, 0x00aa00, 4)
  211.       usersQuantity(true)
  212.       UserBaza, list = {}, {}
  213.       for i = 1, 4 do -- порядок адресов стандартных спавн, ад, край, мир - шахта
  214.         file:write(Baza[i].name..';'..Baza[i].adress..';\n')
  215.         UserBaza[#UserBaza + 1] = {['name'] = Baza[i].name, ['adress'] = Baza[i].adress}
  216.         list[#list + 1] = Baza[i].name
  217.       end
  218.       UserBaza[#UserBaza + 1] = {['name'] = Baza[1].adress, ['adress'] = 'Последняя'}
  219.       list[#list + 1] = Baza[1].name
  220.       file:write(UserBaza[#UserBaza].name..';'..UserBaza[#UserBaza].adress..';\n')
  221.     elseif numBaza == 3 then
  222.       if #Baza>0 then
  223.         for i = 1, #Baza do
  224.           file:write(tostring(Baza[i].name)..';'..tostring(Baza[i].adress)..';'..tostring(Baza[i].access)..';\n')
  225.         end
  226.       else
  227.         errors(13, 7, {'Нет файла', string.sub(files, 1, 30)}, 0x00aa00, 1, false)
  228.         file:write('')
  229.       end
  230.     end  
  231.   else -- если файл найден
  232.     local line = file:read()
  233.     -- print('читаю файл')
  234.     while line do
  235.       local arg = {}
  236.       -- print(arg)os.sleep(0.3)
  237.       for i = 1, numBaza do
  238.         arg[i] = string.sub(line, 1, string.find(line, ';') - 1)
  239.         line = string.sub(line, string.find(line, ';') + 1)
  240.       end
  241.       if numBaza == 2 then
  242.         UserBaza[#UserBaza + 1] = {['name'] = arg[1], ['adress'] = arg[2]}
  243.         list[#list + 1] = arg[1]
  244.       elseif numBaza == 3 then
  245.         Baza[#Baza + 1] = {['name'] = arg[1], ['adress'] = arg[2], ['access'] = toboolean(arg[3])}
  246.       end
  247.       line = file:read()
  248.     end
  249.   end
  250.   if numBaza == 2 then
  251.     UserBaza[1].ends = UserBaza[#UserBaza].name
  252.     UserBaza[#UserBaza] = nil
  253.     list[#list] =  nil
  254.   end
  255.   file:close()
  256. end
  257.  
  258. local function bottom(x, y, text, color) -- большие кнопки
  259.   r = unicode.len(text) + 2
  260.   if color == 0 then color = 0x00ff00 -- зеленый
  261.   elseif color == 1 then color = 0x8b0000 -- красный
  262.   elseif color == 2 then color = 0xBDB76B -- белый?
  263.   elseif color == 3 then color = 0x191970
  264.   elseif color == 4 then color = 0x006400 -- темно - зеленый
  265.   elseif color > 10 then color = color
  266.   else color = 0x008080 -- синеватый
  267.   end
  268.   gpu.setBackground(color)
  269.   gpu.set(x, y, '┏'..("┉"):rep(r)..'┓')
  270.   gpu.set(x, y + 1, '┋ '..text..' ┋')
  271.   gpu.set(x, y + 2, '┗'..("┉"):rep(r)..'┛')
  272.   gpu.setBackground(0x000000)
  273.   gpu.setForeground(0xffffff)
  274.   return y, y + 2, x, x + unicode.len(text) + 3
  275. end
  276.  
  277. local function bottom2(y, text, press) -- маленькие кнопки
  278.   if press then
  279.     F = 0x00ff00
  280.   else
  281.     F = 0x808080
  282.   end
  283.   x = math.floor(22/2 - unicode.len(text)/2) + 30
  284.   gpu.setForeground(F)
  285.   gpu.set(x, y, '◀')
  286.   gpu.set(x + unicode.len(text) + 3, y, '▶')
  287.   gpu.setBackground(F)
  288.   gpu.setForeground(0xffffff)
  289.   gpu.set(x + 1, y, ' '..text..' ')
  290.   gpu.setBackground(0x000000)
  291.   gpu.setForeground(0xffffff)
  292.   return y, y, x, x + unicode.len(text) + 3
  293. end
  294.  
  295. local function bottom3(x, y, text, color) -- вертикальные кнопки
  296.   r = unicode.len(text)
  297.   if color == 0 then color = 0x00ff00 -- зеленый
  298.   elseif color == 1 then color = 0x006400 -- темно - зеленый
  299.   elseif color > 5 then color = color
  300.   else color = 0x008080 -- синеватый
  301.   end
  302.   gpu.setBackground(color)
  303.   gpu.set(x, y, '┏┉┉┉┓')
  304.   for i  = 1, r do
  305.     gpu.set(x, y + i, '┋ '..unicode.sub(text, i, i)..' ┋')
  306.   end
  307.   gpu.set(x, y + r + 1, '┗┉┉┉┛')
  308.   gpu.setBackground(0x000000)
  309.   gpu.setForeground(0xffffff)
  310.   return y, y + r + 1, x, x + 4
  311. end
  312.  
  313. local function bottomPress(y, y1, x, x1) -- нажатие на кнопку
  314.   text = ''
  315.   _, _, c = gpu.get(x, y)
  316.   if y1 - y>3 then
  317.     for i = y + 1, y1 - 1 do
  318.       text = text..gpu.get(x + 2, i)
  319.     end
  320.     bottom3(x, y, text, 0)
  321.     os.sleep(0.5)
  322.     bottom3(x, y, text, c)
  323.     -- print(text)
  324.     return
  325.   end  
  326.   if y ~= y1 then
  327.     for i = x + 2, x1 - 2 do
  328.       text = text..gpu.get(i, y + 1)
  329.     end
  330.     bottom(x, y, text, 0)
  331.     os.sleep(0.5)
  332.     bottom(x, y, text, c)
  333.   else
  334.     for i = x + 2, x1 - 2 do
  335.       text = text..gpu.get(i, y)
  336.     end
  337.     bottom2(y, text, true)
  338.     os.sleep(0.5)
  339.     bottom2(y, text)
  340.   end
  341. end
  342.  
  343. local function onOff(tr) -- преобразование true - >вкл false = >выкл
  344.   if tr then
  345.     tr = 'вкл '
  346.   else
  347.     tr = 'выкл'
  348.   end
  349.   return tr
  350. end
  351.  
  352. local function oval(display) -- заставка врат
  353.   if display then
  354.     gpu.set(9, 2, 'Звездные врата')
  355.     local items = {"Сон через ", "  Статистика:", "Ад:", "Край:", "Мир - шахта: ", "Доступно:  ", "Игроков: ", "Последним был:", " - "}
  356.   for i = 1, 9 do
  357.     gpu.set(9, i + 6, items[i])
  358.   end
  359.   else
  360.     local items = {
  361.     tostring(Temp[2].time)..' ',
  362.     '',
  363.     onOff(Baza[2].access),
  364.     onOff(Baza[3].access),
  365.     onOff(Baza[4].access),
  366.     AllBaza.num,
  367.     usersNum,
  368.     '', Temp[2].name}
  369.     for i = 1, 8 do
  370.       gpu.set(20, i + 6, tostring(items[i]))
  371.     end
  372.     gpu.set(11, 15, tostring(items[9]))
  373.   end
  374. end
  375.  
  376. local function advertising(num, ls) -- Телепорты(и реклама)
  377.   bottomMass2 = {}
  378.   local qua = 0
  379.   gpu.fill(31, 4, 22, 15, ' ')
  380.   gpu.set(30, 2, (" "):rep(23))
  381.   if not ls then
  382.     qua = 7  
  383.     gpu.set(33, 2, 'Точки телепортов')
  384.   else
  385.     qua = 6
  386.     gpu.set(32, 2, 'Ваши точки врат')
  387.     local y0, y1, x0, x1 = bottom2(18, 'Назад')
  388.     bottomMass2[3] = {['y0'] = y0, ['y1'] = y1, ['x0'] = x0, ['x1'] = x1}
  389.   end
  390.   i1 = 0
  391.   num = num - 1
  392.   PrintLine(31, 18, 31, 18, '<=')
  393.   bottomMass2[1] = {['y0'] = 18, ['y1'] = 18, ['x0'] = 31, ['x1'] = 32}
  394.   PrintLine(52, 18, 52, 18, '=>')
  395.   bottomMass2[2] = {['y0'] = 18, ['y1'] = 18, ['x0'] = 52, ['x1'] = 53}
  396.   for i = qua*num + 1, qua*num + qua do
  397.     i1 = i1 + 2
  398.     if list[i] ~= nil then
  399.       local y0, y1, x0, x1 = bottom2(i1 + 3, list[i])
  400.       bottomMass2[#bottomMass2 + 1] = {['y0'] = y0, ['y1'] = y1, ['x0'] = x0, ['x1'] = x1}
  401.     end
  402.   end
  403. end
  404.  
  405. local function bottomSave() -- прорисовка кнопок и запоминания их функционала
  406.   local y0, y0, x0, x1 = 0, 0, 0, 0
  407.   y0, y1, x0, x1 = bottom(4, 4, 'ВХОД', 3) bottomMass[#bottomMass + 1] = {['y0'] = y0, ['y1'] = y1, ['x0'] = x0, ['x1'] = x1}
  408.   y0, y1, x0, x1 = bottom3(3, 7, ' СПАВН ', 1) bottomMass[#bottomMass + 1] = {['y0'] = y0, ['y1'] = y1, ['x0'] = x0, ['x1'] = x1}
  409.   y0, y1, x0, x1 = bottom(7, 16, 'В АД', 1) bottomMass[#bottomMass + 1] = {['y0'] = y0, ['y1'] = y1, ['x0'] = x0, ['x1'] = x1}
  410.   y0, y1, x0, x1 = bottom(17, 16, 'В КРАЙ', 3) bottomMass[#bottomMass + 1] = {['y0'] = y0, ['y1'] = y1, ['x0'] = x0, ['x1'] = x1}
  411.   y0, y1, x0, x1 = bottom(14, 4, 'Мир - шахта', 3) bottomMass[#bottomMass + 1] = {['y0'] = y0, ['y1'] = y1, ['x0'] = x0, ['x1'] = x1}
  412.   y0, y1, x0, x1 = bottom3(24, 7, 'RANDOM ', 2) bottomMass[#bottomMass + 1] = {['y0'] = y0, ['y1'] = y1, ['x0'] = x0, ['x1'] = x1}
  413. end
  414.  
  415. local function bottomMenu(name) -- прорисовка кнопок и запоминания их функционала
  416.   local y0, y0, x0, x1 = 0, 0, 0, 0
  417.   gpu.set(30, 2, (" "):rep(22))
  418.   gpu.set(32, 2, name..', hi')
  419.   gpu.fill(31, 4, 23, 15, ' ')
  420.   y0, y1, x0, x1 = bottom(32, 4, 'В последнюю точку', 1) bottomMass2[#bottomMass2 + 1] = {['y0'] = y0, ['y1'] = y1, ['x0'] = x0, ['x1'] = x1}
  421.   y0, y1, x0, x1 = bottom(32, 8, 'Сохраненные точки', 6) bottomMass2[#bottomMass2 + 1] = {['y0'] = y0, ['y1'] = y1, ['x0'] = x0, ['x1'] = x1}
  422.   y0, y1, x0, x1 = bottom(35, 12, 'Новая точка', 6) bottomMass2[#bottomMass2 + 1] = {['y0'] = y0, ['y1'] = y1, ['x0'] = x0, ['x1'] = x1}
  423.   y0, y1, x0, x1 = bottom(38, 16, 'Выход', 1) bottomMass2[#bottomMass2 + 1] = {['y0'] = y0, ['y1'] = y1, ['x0'] = x0, ['x1'] = x1}
  424. end
  425.  
  426. local function bottomMenuNew() -- прорисовка кнопок и запоминания их функционала
  427.   local y0, y0, x0, x1 = 0, 0, 0, 0
  428.   gpu.set(30, 2, (" "):rep(22))
  429.   gpu.set(33, 2, 'Новая точка врат')
  430.   gpu.fill(31, 4, 23, 15, ' ')
  431.   gpu.set(32, 4, "Имя точки 15 символов")
  432.   gpu.set(32, 6, "_______________")
  433.   bottomMass2[#bottomMass2 + 1] = {['y0'] = 6, ['y1'] = 6, ['x0'] = 32, ['x1'] = 32 + 15}
  434.   gpu.set(32, 8, "Адрес врат")
  435.   gpu.set(32, 10, "_______________")
  436.   bottomMass2[#bottomMass2 + 1] = {['y0'] = 10, ['y1'] = 10, ['x0'] = 32, ['x1'] = 32 + 15}
  437.   y0, y1, x0, x1 = bottom(36, 12, 'Сохранить', 6) bottomMass2[#bottomMass2 + 1] = {['y0'] = y0, ['y1'] = y1, ['x0'] = x0, ['x1'] = x1}
  438.   y0, y1, x0, x1 = bottom(38, 16, 'Назад', 1) bottomMass2[#bottomMass2 + 1] = {['y0'] = y0, ['y1'] = y1, ['x0'] = x0, ['x1'] = x1}
  439. end
  440.  
  441. local function stargateStart() -- проверка на айрис
  442.   stargate.sendMessage('PING')
  443.   status = true
  444.   local _, _, sms = event.pull(5, 'sgMessageReceived')
  445.   if sms == "PONG" then
  446.     stargate.sendMessage('STATUS')
  447.     _, _, sms = event.pull(5, 'sgMessageReceived')
  448.   end
  449.   if sms == 'Offline' or sms == 'Open' then
  450.     sms = 'Айрис открыт'
  451.   elseif sms == nil then
  452.     status = nil
  453.     sms = 'Нет ответа'
  454.   else
  455.     sms = 'ТРЕВОГА! АЙРИС ЗАКРЫТ!'
  456.     status = false
  457.   end
  458.   return sms, status
  459. end
  460.  
  461. local function stargateSend() -- ответ по айрис
  462.   local _, _, sms = event.pull(5, 'sgMessageReceived')
  463.   if sms == "PING" then
  464.     stargate.sendMessage('PONG')
  465.     return true
  466.   elseif sms == "STATUS" then
  467.     stargate.sendMessage(stargate.irisState())
  468.     return true
  469.   else
  470.     return false
  471.   end
  472. end
  473.  
  474. local function printStat(reception) -- окно открытия врат
  475.   local a, i, vr = {}, 0, '##'
  476.   ScreenBuffer(13, 7, 13 + 32, 15, true)
  477.   errors(13, 7, {'Открытие врат', '[----------------------]', '', '', ''}, 0x0000ff, 0, true)
  478.   if reception then
  479.     i = 2
  480.     gpu.set(16, 10, vr)
  481.   end
  482.   gpu.setBackground(0x0000ff)
  483.   repeat
  484.     a = {event.pull(4)}
  485.     if a[1] == 'sgChevronEngaged' then
  486.       i = i + 2
  487.       gpu.set(14 + i, 10, vr)
  488.     elseif a[1] == 'sgStargateStateChange' then
  489.       i = 22
  490.       vr = ('#'):rep(i)
  491.       gpu.set(16, 10, vr)
  492.     end  
  493.     gpu.set(40, 10, math.ceil(i*100/22)..'%')
  494.     if not reception and i == 22 then
  495.       gpu.set(15, 11, 'Ожидаю отчет по айрис ...')
  496.       vr, stat = stargateStart()
  497.       if stat == nil  then
  498.         gpu.set(15, 12, vr)
  499.         gpu.set(15, 13, 'Возможно, айрис закрыт')
  500.       elseif stat == false then
  501.         gpu.set(15, 12, vr)
  502.         gpu.set(15, 13, 'Переход запрещен!')
  503.         stargate.disconnect()
  504.         break;
  505.       else
  506.         gpu.set(15, 12, vr)
  507.         gpu.set(15, 13, 'Переход разрешаю, удачи!')
  508.       end
  509.     elseif reception and i == 22 then
  510.       gpu.set(15, 11, 'Ожидаю проверки моста ...')
  511.       if stargateSend() then
  512.         gpu.set(15, 12, 'Успешно')
  513.       else
  514.         gpu.set(15, 12, 'Нет запроса')
  515.       end
  516.       gpu.set(15, 13, 'Ожидаю проверки айрис ...')
  517.       if stargateSend() then
  518.         gpu.set(15, 14, 'Успешно')
  519.       else
  520.         gpu.set(15, 14, 'Нет запроса')
  521.       end
  522.     end
  523.   until a[1] == nil
  524.   ScreenBuffer(13, 7, 13 + 32, 15, false)
  525.   if a[1] == nil and i == 22 then
  526.     errors(13, 7, {'Врата настроены', 'Переход разрешен, но помните', 'нам неизвестно, что ждет вас', 'на той стороне врат.'}, 0x00aa00, 10, false)
  527.   else
  528.     errors(13, 7, {'ОШИБКА!', 'Произошла ошибка при ', 'построении моста. Переход ', 'запрещен из - за закрытия айрис', 'или по неизвестной причине'}, 0xaa0000, 10, false)
  529.   end
  530. end
  531.  
  532. local function errorBaza() -- стартовый мастер. работает только 1 раз для заполнения основной бызы
  533.   errors(13, 7, {"ERROR", "База не заполнена. Пожалуйста, ", "заполните базу данных вручную ", "в следующем порядке (ВАЖНО!) ", "Cпавн = "..tostring(Baza[1]), "Ад = "..tostring(Baza[2]), "Край = "..tostring(Baza[3]), "Мир - шахта = "..tostring(Baza[4])}, 0xaa0000, nil)
  534.   gpu.setResolution(80, 24)
  535.   print('Мастер быстрой настройки активен')
  536.   print('Желаете настроить базу данных в полуавтоматическом режиме? (y/n)')
  537.   local vr = io.read()
  538.   if vr == 'y' then
  539.     local a = {}
  540.     print('Адрес считывается автоматически, вам надо заполнить только остальную информацию')
  541.     print('Адрес текущих врат '..stargate.localAddress()..'\nЕсли адрес другой, введите его, если совпадает, нажмите Enter')
  542.     vr = io.read()
  543.     os.sleep(0.1)
  544.     local i = #Baza + 1
  545.     if vr == '' then
  546.       a[#a + 1] = stargate.localAddress()
  547.     else
  548.       a[#a + 1] = vr
  549.     end
  550.     print('Где мы находимся? (введите название этих врат)')
  551.     vr = io.read()
  552.     os.sleep(0.1)
  553.     if vr == '' then
  554.       print('ERROR! Имя не может быть пустым!')
  555.       os.exit()
  556.     else
  557.       a[#a + 1] = vr
  558.     end
  559.     print('Разрешить доступ к этим вратам? (введите true/false)')
  560.     vr = io.read()
  561.     os.sleep(0.1)
  562.     if vr == '' then
  563.       print('ERROR! Доступ не может быть пустым!')
  564.       os.exit()
  565.     else
  566.       a[#a + 1] = vr
  567.     end
  568.     print('Сохраняю ...')
  569.     Baza[#Baza + 1] = {['name'] = a[2], ['adress'] = a[1], ['access'] = a[3]}
  570.     print('В память базы записано')
  571.     AllBaza[#AllBaza + 1] = a[1]
  572.     print('В память общих точек записано')
  573.     openFile(nil, 3, true)
  574.     print('База сохранена')
  575.     bazaAdress(false, true)
  576.     print('Случайная база сохранена')
  577.     print('Все сохранено. Переместитесь к следующим вратам и сохраните их. Диск можете с собой утащить. Напомню порядок: Cпавн, Ад, Край, Мир - шахта\nВсе остальные точки врат можно будет настроить через нормальное меню')
  578.   else
  579.     print('Для ручной настройки заполните файл ../Stargate/System/Baza.csv по образцу \n[Имя];[Адрес];[Доступность];\n Пример:\nСпавн;UYBM - 6ZK - SA;true;')
  580.   end
  581.   os.exit()
  582. end
  583.  
  584. local function errorDial(vr) -- ответ на разнообразные ошибки
  585.   if string.find(vr, 'busy')  ~=  nil then
  586.     errors(13, 7, {'ОШИБКА!', 'Данные врата уже подключены к', 'другому мосту. ', 'Подождите 30 секунд и', 'повторите попытку'}, 0xaa0000, 10, false)
  587.   elseif vr == 'Stargate cannot connect to itself' then
  588.     errors(13, 7, {'ОШИБКА!', 'Вы пытаетесь подключиться к ', 'этим же вратам.', 'Будьте внимательны при наборе'}, 0xaa0000, 10, false)
  589.   elseif vr == 'Malformed stargate address' then
  590.     errors(13, 7, {'ОШИБКА!', 'Некорректный ввод адреса.', 'Будьте внимательны при наборе'}, 0xaa0000, 10, false)
  591.   elseif string.find(vr, 'chevrons')  ~=  nil then
  592.     errors(13, 7, {'ОШИБКА!', 'Не хватает шевронов для', 'перехода в указанную вами', 'точку. Добавьте еще 1 шеврон', 'и повторите попытку'}, 0xaa0000, 10, false)
  593.   elseif vr == nil then
  594.     return
  595.   else
  596.     errors(13, 7, {'ОШИБКА!', 'Данных врат не существует.', 'Будьте внимательны при наборе'}, 0xaa0000, 10, false)
  597.   end
  598. end
  599.  
  600. local function editPoint(num, name) -- удаление пользовательских точек
  601.   if errors(13, 7, {'Информация по точке', 'Имя: '..UserBaza[num].name, 'Адрес: '..UserBaza[num].adress, 'ПКМ - удалить', 'ЛКМ - обратно'}, 0x0000ff, 10, false, name) then
  602.     -- print('удаляю')
  603.     table.remove(UserBaza, num)
  604.     openFile(name, 2, false, true)
  605.     UserBaza = {}
  606.     list = {}
  607.     openFile(name, 2)
  608.     bottomMass2 = {}
  609.     advertising(1, true)
  610.     Temp[1].list = 1
  611.   end
  612. end
  613.  
  614. local function touchOn(x, y, name, key) -- обработчик нажатий
  615.   if x >= 2 and x <= 29 and menu  <=  1 then -- главное меню
  616.     for i  = 1, #bottomMass do
  617.    -- print(tostring(bottomMass[i].y0  >=  a[4])..'|'..tostring(bottomMass[i].y1  <=  a[4])..'|'..tostring(bottomMass[i].x0 <= a[3])..'|'..tostring(bottomMass[i].x1 >= a[3]))
  618.       if bottomMass[i].y0  <=  a[4] and bottomMass[i].y1  >=  a[4] and bottomMass[i].x0 <= a[3] and bottomMass[i].x1 >= a[3] then
  619.         if bottomMass[i].y1 - bottomMass[i].y0>3 then
  620.           bottomPress(bottomMass[i].y0, bottomMass[i].y1, bottomMass[i].x0, bottomMass[i].x1, true)
  621.         else
  622.           bottomPress(bottomMass[i].y0, bottomMass[i].y1, bottomMass[i].x0, bottomMass[i].x1)
  623.         end
  624.         if i == 1 then
  625.           bottomMass2 = {}
  626.           bottomMenu(name)
  627.           menu = 2
  628.           Temp[2].name1 = name
  629.           -- openFile(name, 2, true) -- убрать, это для теста
  630.           UserBaza = {}
  631.           list = {}
  632.           openFile(name, 2)
  633.         elseif i == 6 then
  634.           -- print('RANDOM')
  635.           bazaAdress(false, false, false, true)
  636.           stargate.disconnect()
  637.           os.sleep(2)
  638.           local _, vr = stargate.dial(Baza[i - 1].adress)
  639.           if vr ~= nil then
  640.             errorDial(vr)
  641.           end
  642.         else
  643.           stargate.disconnect()
  644.           -- print(Baza[i - 1].adress..'|'..Baza[i - 1].name..'|'..i - 1)
  645.           if Baza[i - 1].access then
  646.             os.sleep(2)
  647.             local _, vr = stargate.dial(Baza[i - 1].adress)
  648.             if vr ~= nil then
  649.               errorDial(vr)
  650.             end
  651.           else
  652.             errors(13, 7, {'ОШИБКА!', 'Переход в текущую точку', 'запрещен администратором'}, 0xaa0000, 10)
  653.           end
  654.         end
  655.         return
  656.       end
  657.     end
  658.   elseif x >= 31 and x <= 53 and menu == 2 then -- меню входа
  659.     if name == Temp[2].name1 then
  660.     for i  = 1, #bottomMass2 do
  661.       if bottomMass2[i].y0  <=  a[4] and bottomMass2[i].y1  >=  a[4] and bottomMass2[i].x0 <= a[3] and bottomMass2[i].x1 >= a[3] then
  662.         bottomPress(bottomMass2[i].y0, bottomMass2[i].y1, bottomMass2[i].x0, bottomMass2[i].x1)
  663.         if i == 1 then
  664.           stargate.disconnect()
  665.           os.sleep(2)
  666.           local _, vr = stargate.dial(UserBaza[1].ends)
  667.           if vr ~= nil then
  668.             errorDial(vr)
  669.           end
  670.         elseif i == 2 then
  671.           menu = 4
  672.           bottomMass2 = {}
  673.           advertising(1, true)
  674.           Temp[1].list = 1
  675.         elseif i == 3 then
  676.           bottomMass2 = {}
  677.           bottomMenuNew()
  678.           menu = 3
  679.           Temp[1] = {['name'] = '', ['adress'] = ''}
  680.           -- print(#UserBaza..' menu '..menu)
  681.         elseif i == 4 then
  682.           bottomMass2 = {}
  683.           list = {}
  684.           for i = 5, #Baza do
  685.             list[#list + 1] = Baza[i].name
  686.           end
  687.           advertising(1)
  688.           Temp[2].name1 = ''
  689.           Temp[1].list = 1
  690.           menu = 1
  691.         end
  692.         return
  693.       end
  694.     end
  695.     end    
  696.   elseif x >= 31 and x <= 53 and menu == 3 then -- меню новая точка
  697.     for i  = 1, #bottomMass2 do
  698.       if bottomMass2[i].y0  <=  a[4] and bottomMass2[i].y1  >=  a[4] and bottomMass2[i].x0 <= a[3] and bottomMass2[i].x1 >= a[3] then
  699.         if i == 1 then
  700.           term.setCursor(32, 6)
  701.           Temp[1].name = unicode.sub(io.read(), 1, 15)
  702.         elseif i == 2 then
  703.           term.setCursor(32, 10)
  704.           Temp[1].adress = unicode.sub(io.read(), 1, 15)
  705.         elseif i == 3 then
  706.           if name == Temp[2].name1 then
  707.           if Temp[1].name  ~=  '' and Temp[1].adress  ~= '' then
  708.             bottomPress(bottomMass2[i].y0, bottomMass2[i].y1, bottomMass2[i].x0, bottomMass2[i].x1)
  709.             UserBaza[#UserBaza + 1] = {['name'] = Temp[1].name, ['adress'] = Temp[1].adress}
  710.             openFile(name, 2, false, true)
  711.             errors(13, 7, {'Сохранено!', 'Точка врат добавлена.', 'Рекомендую проверить её работу'}, 0x00aa00, 3)
  712.             bazaAdress(false, Temp[1].adress)
  713.             bazaAdress(false, false, true)
  714.             bottomMass2 = {}
  715.             bottomMenu(name)
  716.             menu = 2
  717.             UserBaza = {}
  718.             list = {}
  719.             openFile(name, 2)
  720.           else
  721.             errors(13, 7, {'ОШИБКА!', 'Некорректный ввод названия ', 'точки телепорта или адреса ', 'врат. Проверьте еще раз прави - ', 'льность ввода. В случае ', 'повторения ошибки, запишите её', 'на видео и предоставьте админу'}, 0xaa0000, 10)
  722.             bottomMenuNew()
  723.           end
  724.           end
  725.         elseif i == 4 then
  726.           bottomPress(bottomMass2[i].y0, bottomMass2[i].y1, bottomMass2[i].x0, bottomMass2[i].x1)
  727.           bottomMass2 = {}
  728.           bottomMenu(name)
  729.           menu = 2
  730.           UserBaza = {}
  731.           list = {}
  732.           openFile(name, 2)
  733.         end
  734.         return
  735.       end
  736.     end
  737.   elseif x >= 31 and x <= 53 and menu == 4 then -- меню телепортов пользователя
  738.     if name == Temp[2].name1 then
  739.     for i  = 1, #bottomMass2 do
  740.       if bottomMass2[i].y0  <=  a[4] and bottomMass2[i].y1  >=  a[4] and bottomMass2[i].x0 <= a[3] and bottomMass2[i].x1 >= a[3] then
  741.         if i == 1 then
  742.           print(tonumber(Temp[1].list))
  743.           if Temp[1].list - 1 > 0 then
  744.             Temp[1].list = Temp[1].list - 1
  745.             advertising(Temp[1].list, true)
  746.           end
  747.         elseif i == 2 then
  748.           if Temp[1].list + 1  <=  math.ceil(#list/6) then
  749.             Temp[1].list = Temp[1].list + 1
  750.             advertising(Temp[1].list, true)
  751.           end
  752.         elseif i == 3 then
  753.           bottomPress(bottomMass2[i].y0, bottomMass2[i].y1, bottomMass2[i].x0, bottomMass2[i].x1)
  754.           menu = 2
  755.           bottomMass2 = {}
  756.           bottomMenu(name)
  757.         else
  758.           if key == 1 then
  759.             bottomPress(bottomMass2[i].y0, bottomMass2[i].y1, bottomMass2[i].x0, bottomMass2[i].x1)
  760.             editPoint((i - 3) + (Temp[1].list - 1)*6, name)
  761.           else
  762.             bottomPress(bottomMass2[i].y0, bottomMass2[i].y1, bottomMass2[i].x0, bottomMass2[i].x1)
  763.             stargate.disconnect()
  764.           -- print(list[(i - 3) + (Temp[1].list - 1)*6]..'|'..UserBaza[(i - 3) + (Temp[1].list - 1)*6].name..'|'..i)
  765.             UserBaza[1].ends = UserBaza[(i - 3) + (Temp[1].list - 1)*6].adress
  766.             openFile(name, 2, false, true)
  767.             os.sleep(2)
  768.             local _, vr = stargate.dial(UserBaza[1].ends)
  769.             if vr ~= nil then
  770.               errorDial(vr)
  771.             end
  772.           end
  773.         end
  774.         return
  775.       end
  776.     end
  777.     end
  778.  
  779.   elseif x >= 31 and x <= 53 and menu  <=  1 then -- меню телепортов официальных
  780.     for i  = 1, #bottomMass2 do
  781.       if bottomMass2[i].y0  <=  a[4] and bottomMass2[i].y1  >=  a[4] and bottomMass2[i].x0 <= a[3] and bottomMass2[i].x1 >= a[3] then
  782.         if i == 1 then
  783.           if Temp[1].list - 1 > 0 then
  784.             Temp[1].list = Temp[1].list - 1
  785.             advertising(Temp[1].list)
  786.           end
  787.         elseif i == 2 then
  788.           if Temp[1].list + 1  <=  math.ceil(#list/7) then
  789.             Temp[1].list = Temp[1].list + 1
  790.             advertising(Temp[1].list)
  791.           end
  792.         else
  793.           bottomPress(bottomMass2[i].y0, bottomMass2[i].y1, bottomMass2[i].x0, bottomMass2[i].x1)
  794.           stargate.disconnect()
  795.           -- print(list[(i - 2) + (Temp[1].list - 1)*7]..'|'..Baza[(i + 2) + (Temp[1].list - 1)*7].name)
  796.           if Baza[(i + 2) + (Temp[1].list - 1)*7].access then
  797.             os.sleep(2)
  798.             local _, vr = stargate.dial(Baza[(i + 2) + (Temp[1].list - 1)*7].adress)
  799.             if vr ~= nil then
  800.               errorDial(vr)
  801.             end
  802.           else
  803.             errors(13, 7, {'ОШИБКА!', 'Переход в текущую точку', 'запрещен администратором'}, 0xaa0000, 10)
  804.           end
  805.         end
  806.         return
  807.       end
  808.     end
  809.    
  810.   end
  811. end
  812.  
  813.  
  814.  ----------- ПЕРЕМЕННЫЕ ----------------------
  815.  
  816. Buffer = {} -- буфер для графики (Оторожно, выжирает почти всю память)
  817. gpu.setResolution(54, 19)
  818. term.clear()
  819. bottomMass = {} -- кнопки большие
  820. bottomMass2 = {} -- кнопки маленькие
  821. Baza = {} -- главные точки врат
  822. UserBaza = {} -- пользовательские точки врат
  823. AllBaza = {} -- хранит все адреса
  824. list = {} -- список адресов для маленьких кнопок
  825. if not fl.exists("../Stargate") then
  826.   print('нету ../Stargate')
  827.   fl.makeDirectory("../Stargate/Users/")
  828.   fl.makeDirectory("../Stargate/System/")
  829.   openFile(nil, 3, true)
  830.   bazaAdress(true)
  831. end
  832. openFile(nil, 3)
  833. if #Baza < 4 then
  834.   errorBaza()
  835. end
  836. event.shouldInterrupt = function () return false end --защита от ctrl+alt+c
  837. Temp = {} -- временные данные
  838. Temp[1] = {['name'] = '', ['adress'] = '', ['list'] = 1}
  839. Temp[2] = {['time'] = 1, ['name'] = 'ХЗ', ['name1'] = ''}
  840. bazaAdress(false, false, true)
  841. usersQuantity(false)
  842. print('LOADING ...')
  843. local name = ''
  844.  
  845.  ---------------- ОСНОВНОЙ ЦИКЛ ------------------------
  846.  
  847. repeat
  848.   a = {event.pull(1)}
  849.   if a[1] == 'sgStargateStateChange' or a[1] == 'sgDialIn' and a[3] ~=  'Closing' then
  850.     a = {event.pull(1)}
  851.     if a[1] == 'sgDialOut' then
  852.       -- print('передатчик')
  853.       printStat(false)
  854.     else
  855.       -- print('приемник')
  856.       printStat(true)
  857.     end
  858.   elseif a[1] == 'touch' then
  859.     touchOn(a[3], a[4], a[6], a[5])
  860.     name = a[6]
  861.     Temp[2].time = 30
  862.       -- gpu.set(33, 4, 'x = '..a[3]..' y = '..a[4]..'  ')
  863.   elseif a[1] == nil then
  864.     Temp[2].time = Temp[2].time - 1
  865.     oval()
  866.     if Temp[2].time  <=  0 then
  867.       Temp[2].time = 30
  868.       Temp[2].name = name
  869.       Temp[2].name1 = ''
  870.       name = ''
  871.       menu = 1
  872.       stargate.disconnect()
  873.       errors(13, 7, {'Информация', 'Система переведена в режим ', 'ожидания, для активации ', 'нажмите куда - нибудь'}, 0x00aa00, nil, false)
  874.       term.clear()
  875.       frame()
  876.       oval(true)
  877.       bottomSave()
  878.       Baza = {}
  879.       openFile(nil, 3)
  880.       list = {}
  881.       for i = 5, #Baza do
  882.         list[#list + 1] = Baza[i].name
  883.       end
  884.       advertising(1)
  885.       oval()
  886.     end
  887.   end
  888. until a[1] == 'key_up' and a[4] == 59
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement