Advertisement
Guest User

OpenBc.lua

a guest
Apr 1st, 2020
1,174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 17.13 KB | None | 0 0
  1. -- Max K / 07.06.2017 / mcskill.ru
  2.  
  3. local component = require("component")
  4. local computer = require("computer")
  5. local term = require("term")
  6. local event = require("event")
  7. local serialization = require("serialization")
  8. local unicode = require("unicode")
  9. local gpu = component.gpu
  10.  
  11.  
  12. event.shouldInterrupt = function() return false end
  13.  
  14. local masters = {
  15.     Shyvana = 1,
  16.     Astro = 1,
  17. }
  18. function startup()
  19.     local setf = gpu.setForeground
  20.     term.clear()
  21.     io.write("проверка мониторов")
  22.     for i = 1,3 do
  23.         os.sleep(0.2)
  24.         io.write(" .")
  25.     end
  26.    
  27.     local w,h = component.screen.getAspectRatio()
  28.     if w == 7 and h == 3 then
  29.         setf(0x00ff00)
  30.         io.write(" ok\n")
  31.         setf(0xffffff)
  32.         os.sleep(1)
  33.     else
  34.         setf(0xff0000)
  35.         io.write(" failed\n")
  36.         setf(0xffffff)
  37.         io.write("нужен экран 7 блоков в ширину и 3 в высоту,\n")
  38.         io.write("а у тебя " .. w .. " в ширину и " .. h .. " в высоту\n\n")
  39.         os.sleep(5)
  40.         os.exit()
  41.     end
  42.     io.write("проверка чатбокса ")
  43.     for i = 1,3 do
  44.         os.sleep(0.2)
  45.         io.write(" .")
  46.     end
  47.  
  48.     if component.isAvailable("chat_box") == true then
  49.         setf(0x00ff00)
  50.         io.write(" ok\n")
  51.         setf(0xffffff)
  52.         os.sleep(2)
  53.     else
  54.         setf(0xff0000)
  55.         io.write(" failed\n")
  56.         setf(0xffffff)
  57.         io.write("подключи творческий чатбокс")
  58.         os.sleep(5)
  59.         os.exit()
  60.     end
  61. end
  62. --startup()
  63. local chat = component.chat_box
  64. --gpu.setResolution(140,28)
  65. gpu.setResolution(160,28)
  66. local timers = {}
  67. function ioLoad()
  68.     local f,err = io.open("/home/_timers","r")
  69.     if err then
  70.         local t = {}
  71.         ff,errr = io.open("/home/_timers","w")
  72.         if errr then
  73.             error("kappa")
  74.         end
  75.         ff:write(serialization.serialize(t))
  76.         ff:close()
  77.     else
  78.         local a = f:read()
  79.         f:close()
  80.         timers = serialization.unserialize(a)
  81.     end
  82. end
  83. ioLoad()
  84. local buttons = {}
  85. chat.setName("§4O§7")
  86. local name2
  87. --local name2 = "§8[§eВестник§8]§f : "
  88.  
  89. function loadName2()
  90.     local f,err = io.open("/home/_name2","r")
  91.     if err then
  92.         local name2 = "§8[§eВестник§8]§a kappa§f: "
  93.         ff,errr = io.open("/home/_name2","w")
  94.         if errr then
  95.             error("kappa5")
  96.         end
  97.         ff:write(name2)
  98.         ff:close()
  99.         loadName2()
  100.     else
  101.         local a = f:read()
  102.         f:close()
  103.         name2 = a
  104.     end
  105. end
  106. loadName2()
  107. function saveName2()
  108.     local f,err = io.open("/home/_name2","w")
  109.     if err then
  110.         error("ошибка saveName2()")
  111.     end
  112.     f:write(name2)
  113.     f:close()
  114.  
  115. end
  116. local lastOperator = ""
  117. local c = {
  118.     buttonOutlineDef = 0x00ff00,
  119.     buttonFgDef = 0xFFFFFF,
  120.     buttonBgDef = 0x222222,
  121.     delayColorDef = 0xFFFFFF,
  122.     delayColorInf = 0xff9900,
  123.     listenColor = 0xffffff,
  124.     idColor = 0xbababa,
  125.     disabledColor = 0xbababa,
  126.     broadcastColorDef = 0xffffff,
  127.     removeColor = 0xFF0000,
  128.     delayButtonString = "delay: ",
  129.     removeButtonString = "remove",
  130.     buttonOutlineDefStart = "[",
  131.     buttonOutlineDefEnd = "]",
  132.     offset_delete = 1,
  133.     offset_broadcast = 10,
  134.     offset_listen = 22,
  135.     offset_paused = 31,
  136.     offset_repeatDelay = 49,
  137.     offset_id = 40,
  138.     offset_text = 76,
  139.     offset_edit1 = 64,
  140.     maxwidth_repeatDelay = 14,
  141.     maxwidth_id = 9,
  142.     maxwidth_edit1 = 15,
  143.     maxwidth_text = 100,
  144.     pausedText = "paused",
  145.     unpausedText = "active",
  146.     pausedColor = 0xff9900,
  147.     unpausedColor = 0x00ff00,
  148.     unpausedInactiveColor = 0xa76805,
  149.     readingFromChatMsgBackground = 0x6e6e6e,
  150.     textFieldMaxLength = 50,
  151.     helpWidth = 112,
  152. }
  153.  
  154. buttonOutlineDefStartLength = unicode.len(c.buttonOutlineDefStart)
  155. buttonOutlineDefEndLength = unicode.len(c.buttonOutlineDefEnd)
  156. screenWidth, screenHeight = gpu.getResolution()
  157. maxTimersAllowed = screenHeight-3
  158.  
  159.  
  160. local helpStrings = {
  161.     "       |ff0000[remove]|ffffff - удалить объявление",
  162.     "    |00ff00[|ffffffbroadcast|00ff00]|ffffff - пустить объявление 1 раз в общий чат вне очереди",
  163.     "       |00ff00[|fffffflisten|00ff00]|ffffff - пустить объявление 1 раз в локальный чат",
  164.     "|00ff00[active|ffffff/|ff9900paused]|ffffff - поставить объявление на паузу и обратно:",
  165.     "                  |00ff00[active]|ffffff - объявление активно",
  166.     "                  |ff9900[paused]|ffffff - объявление на паузе. не даст снять с паузы если не заполнен текст или задержка",
  167.     "          |bababa[id:]|ffffff - id таймера для отладки",
  168.     "       |00ff00[|ffffffdelay:|00ff00]|ffffff - задержка между сообщениями в секундах (чем больше тем реже будут появляться сообщения)",
  169.     "                  |ff9900delay: inf|ffffff значит что задержка не указана (сообщение не будет выводиться)",
  170.     "                  если что, 5 минут = 300 секунд",
  171.     "    |00ff00[|ffffffchat edit|00ff00]|ffffff - редактировать объявление, используя чат (текст объявления нужно будет ввести в чат игры)",
  172.     "                  введи |17d4fdcancel|ffffff для отмены",
  173.     "         |00ff00[|fffffftext|00ff00]|ffffff - последнее поле - сам текст объявления. можно редактировать, нажав на него мышкой.",
  174.     "                  вставлять скопированный текст клавишей |17d4fdinsert|ffffff. вызвать предыдущий текст - |17d4fdстрелка вверх",
  175.     "                  |17d4fdenter|ffffff для сохранения изменений. оставить поле пустым для отмены. |ff9900n/a|ffffff - текст отсутствует",
  176.     "                  можно вводить форматирование и цвета символом |17d4fd&|ffffff  ",
  177.     "",
  178.     "выходить из проги только кнопкой |00ff00[|ffffffreboot|00ff00]|ffffff, или ручной перезагрузкой компа",
  179.     "после повторного включения все объявления станут на паузу",
  180. }
  181. c.helpHeight = #helpStrings
  182. function say(msg)
  183.     component.chat_box.say("§bbroadcaster§7: " .. tostring(msg),20)
  184. end
  185. function listen(msg)
  186.     if msg ~= "" then
  187.         msg = msg:gsub("&","§")
  188.         component.chat_box.say("[local] " .. name2 .. tostring(msg),20)
  189.     end
  190. end
  191. function broadcast(msg)
  192.     if msg ~= "" then
  193.         msg = msg:gsub("&","§")
  194.         component.chat_box.say(name2 .. tostring(msg)) -- убрать 20 для глобала
  195.     end
  196. end
  197. function log(msg,color)
  198.     local oldFg = gpu.getForeground()
  199.     if color then
  200.         gpu.setForeground(color)
  201.     end
  202.     io.write(msg .. "\n")
  203.     if color then
  204.         gpu.setForeground(oldFg)
  205.     end
  206. end
  207. function ioSave()
  208.     local f,err = io.open("/home/_timers","w")
  209.     if err then
  210.         error("ошибка ioSave()")
  211.     end
  212.     f:write(serialization.serialize(timers))
  213.     f:close()
  214. end
  215. function addBroadcast(timer,msg,isPaused)
  216.     checkArg(1,timer,"number")
  217.     checkArg(2,msg,"string")
  218.     checkArg(3,isPaused,"boolean","nil")
  219.     local id = event.timer(timer,function() broadcast(msg) end, math.huge)
  220.     table.insert(timers,{id = id, repeatDelay = timer, paused = isPaused or false, msg = msg})
  221. end
  222. function removeBroadcast(index,x,y)
  223.     checkArg(1,index,"number")
  224.     local oldbg = gpu.getBackground()
  225.     local oldfg = gpu.getForeground()
  226.     gpu.setBackground(0xFFFFFF)
  227.     gpu.setForeground(0x000000)
  228.     gpu.set(x,y,"[remove]")
  229.     gpu.setForeground(oldfg)
  230.     gpu.setBackground(oldbg)
  231.     local evt,_,X,Y,_,NAME = event.pull("touch")
  232.         if X >= x and X <= x+unicode.len(c.removeButtonString)+buttonOutlineDefStartLength+buttonOutlineDefEndLength and Y == y and NAME == lastOperator then
  233.  
  234.             if timers[index].paused == false then
  235.                 if event.cancel(timers[index].id) then
  236.                 else
  237.                     say("wrong timer id")
  238.                     error("kappa2")
  239.                 end
  240.             end
  241.             table.remove(timers,index)
  242.    
  243.     end
  244. end
  245. function switchPauseStatus(index)
  246.     checkArg(1,index,"number")
  247.     if timers[index].paused == false then
  248.         if event.cancel(timers[index].id) then
  249.             timers[index].paused = true
  250.             timers[index].id = 0
  251.         else
  252.             error("kappa3")
  253.         end
  254.     elseif timers[index].paused == true then
  255.         if timers[index].repeatDelay ~= math.huge and timers[index].msg ~= "" then
  256.             local newid = event.timer(timers[index].repeatDelay,function() broadcast(timers[index].msg) end, math.huge)
  257.             timers[index].id = newid
  258.             timers[index].paused = false
  259.         end
  260.     end
  261. end
  262. function addButton(x,y,text,fg,bg,outline,maxWidth,functi,...)
  263.     buttons[#buttons+1] = {
  264.         x = x,
  265.         y = y,
  266.         text = text,
  267.         textLen = unicode.len(text),
  268.         fg = fg or c.buttonFgDef,
  269.         bg = bg or c.buttonBgDef,
  270.         outline = outline or c.buttonOutlineDef,
  271.         maxWidth = maxWidth or nil,
  272.         func = functi,
  273.         args = {...}
  274.     }
  275. end
  276. function addButton2(x,y,text,fg,bg,outline,maxWidth,functi,...)
  277.     buttons2[#buttons+1] = {
  278.         x = x,
  279.         y = y,
  280.         text = text,
  281.         textLen = unicode.len(text),
  282.         fg = fg or c.buttonFgDef,
  283.         bg = bg or c.buttonBgDef,
  284.         outline = outline or c.buttonOutlineDef,
  285.         maxWidth = maxWidth or nil,
  286.         func = functi,
  287.         args = {...}
  288.     }
  289. end
  290. function getTimersCount()
  291.     local count = 0
  292.     for k,v in pairs(timers) do
  293.         count = count + 1
  294.     end
  295.     return count
  296. end
  297. function draw(table)
  298.     local oldfg = gpu.getForeground()
  299.     local oldbg = gpu.getBackground()
  300.     local timersCount = getTimersCount()
  301.     if table == buttons or table == nil then
  302.         for k,this in pairs(buttons) do
  303.             gpu.setForeground(this.outline)
  304.             gpu.setBackground(this.bg)
  305.             gpu.set(this.x,this.y,c.buttonOutlineDefStart)
  306.             gpu.set(this.x+unicode.len(this.text)+buttonOutlineDefStartLength,this.y,c.buttonOutlineDefEnd)
  307.             gpu.setForeground(this.fg)
  308.             gpu.set(this.x+buttonOutlineDefStartLength,this.y,this.text)
  309.             if this.maxWidth then
  310.                 local diff = this.maxWidth - (unicode.len(this.text)+buttonOutlineDefStartLength+buttonOutlineDefEndLength)
  311.                 if diff > 0 then
  312.                     gpu.setBackground(oldbg)
  313.                     gpu.set(this.x+unicode.len(this.text)+buttonOutlineDefStartLength+buttonOutlineDefEndLength,this.y,string.rep(" ",diff))
  314.                 end
  315.             end
  316.         end
  317.         gpu.setForeground(oldfg)
  318.         gpu.setBackground(oldbg)
  319.         if timersCount < maxTimersAllowed then
  320.             gpu.fill(1,timersCount+1,screenWidth,maxTimersAllowed-timersCount," ")
  321.         end
  322.     end
  323.     gpu.setForeground(oldfg)
  324.     gpu.setBackground(oldbg)
  325. end
  326. function getEvent()
  327.     local evt,_,X,Y,_,name = event.pull("touch")
  328.     --if masters[name] then
  329.         for k,this in pairs(buttons) do
  330.             if X >= this.x and X <= this.x+this.textLen+buttonOutlineDefStartLength+buttonOutlineDefEndLength and Y == this.y then
  331.                 if this.func then
  332.                     lastOperator = name
  333.                     this.func(table.unpack(this.args))
  334.                 end
  335.             end
  336.         end
  337.     --end
  338. end
  339. function editDelay(x,y,index)
  340.     gpu.set(x+1,y,string.rep(" ",c.maxwidth_repeatDelay-buttonOutlineDefStartLength-buttonOutlineDefEndLength))
  341.     term.setCursor(x+1,y)
  342.     local newValue = io.read()
  343.     newValue = tonumber(newValue)
  344.     if newValue == nil then
  345.         return
  346.     else
  347.         newValue = math.floor(newValue)
  348.     end
  349.     if newValue > 99999 or newValue <= 0 then
  350.         newValue = math.huge
  351.     end
  352.     switchPauseStatus(index)
  353.     timers[index].repeatDelay = newValue
  354.     switchPauseStatus(index)
  355. end
  356. function editMsg(x,y,index)
  357.     gpu.fill(x+1,y,unicode.len(getButtonLabel(index)),1," ")
  358.     term.setCursor(x+1,y)
  359.     local param = {[1] = timers[index].msg, nowrap = true}
  360.     local newValue = term.read(param)
  361.     if string.sub(newValue,0,-2) == "" then
  362.         return true
  363.     else
  364.         switchPauseStatus(index)
  365.         newValue = string.sub(newValue,0,-2)
  366.         timers[index].msg = newValue
  367.         switchPauseStatus(index)
  368.     end
  369. end
  370. function editMsgThroughChat(x,y,index)
  371.     function getNextPlayerMessage(player)
  372.         while true do
  373.             local evt,_,name,msg = event.pull("chat_message")
  374.             if name == player and string.find(msg,"!") ~= 1 and msg ~= "cancel" then
  375.                 return msg
  376.             elseif msg == "cancel" then
  377.             --and masters[name] then
  378.                 return nil
  379.             end
  380.         end
  381.     end
  382.  
  383.     gpu.fill(x+1,y,unicode.len(getButtonLabel(index)),1," ")
  384.     local oldbg = gpu.getBackground()
  385.     gpu.setBackground(c.readingFromChatMsgBackground)
  386.     gpu.set(x+1,y,"reading from chat (type \"cancel\" to cancel) ... ")
  387.     gpu.setBackground(oldbg)
  388.     local res = getNextPlayerMessage(lastOperator)
  389.     if res then
  390.         switchPauseStatus(index)
  391.         timers[index].msg = res
  392.         switchPauseStatus(index)
  393.     else
  394.         say("отмена")
  395.     end
  396. end
  397. function getButtonLabel(index)
  398.     local label
  399.     if unicode.len(timers[index].msg) > c.textFieldMaxLength then
  400.         label = unicode.sub(timers[index].msg,0,(unicode.len(timers[index].msg)-c.textFieldMaxLength-3)*-1) .. "..."
  401.     else
  402.         label = timers[index].msg
  403.     end
  404.     return label
  405. end
  406. function buttonAddBroadcast()
  407.     --addBroadcast(math.huge,"",true)
  408.     if getTimersCount() < maxTimersAllowed then
  409.         table.insert(timers,{id = 0, repeatDelay = math.huge, paused = true, msg = ""})
  410.     end
  411. end
  412. function buttonBroadcast(index)
  413.     broadcast(timers[index].msg)
  414. end
  415. function buttonReboot()
  416.     computer.shutdown(1)
  417. end
  418.  
  419. function drawWindow(x,y,w,h)
  420.     gpu.fill(x,y,w,h," ")
  421.     gpu.set(x,y,string.rep("⠒",w))
  422.     gpu.set(x,y+h,string.rep("⠤",w))
  423.     gpu.set(x,y,string.rep("⡇",h),true)
  424.     gpu.set(x+w,y,string.rep("⢸",h),true)
  425.    
  426.     gpu.set(x,y,"⡖")
  427.     gpu.set(x+w,y,"⢲")
  428.     gpu.set(x,y+h,"⠧")
  429.     gpu.set(x+w,y+h,"⠼")
  430. end
  431. function drawText(x,y,array)
  432.     function printLine(string)
  433.         if string ~= "" then
  434.             local a,b = string.find(string,"|........")
  435.             if a == nil then
  436.                 io.write(string)
  437.                 gpu.setForeground(0xffffff)
  438.             elseif a > 1 then
  439.                 io.write(string:sub(0,a-1))
  440.                 printLine(string:sub(a))
  441.             elseif a == 1 then
  442.                 gpu.setForeground(tonumber("0x" .. string:sub(2,7)))
  443.                 string = string:sub(7+1)
  444.                 printLine(string)
  445.             end
  446.         else
  447.             gpu.setForeground(0xffffff)
  448.             return true
  449.         end
  450.     end
  451.  
  452.     local i = 0
  453.     for k,v in pairs(array) do
  454.         term.setCursor(x,y+i)
  455.         printLine(v)
  456.         i = i+1
  457.     end
  458. end
  459. function showHelp()
  460.     local x = math.floor((screenWidth-c.helpWidth)/2)
  461.     local y = 3
  462.    
  463.     drawWindow(x,y,c.helpWidth,c.helpHeight+1)
  464.     drawText(x+2,y+1,helpStrings)
  465.  
  466.     while true do
  467.         local evt,_,X,Y,_,NAME = event.pull("touch")
  468.         --if masters[NAME] then
  469.             gpu.fill(x,y,c.helpWidth+1,c.helpHeight-y+2," ")
  470.             break
  471.         --end
  472.     end
  473. end
  474.  
  475. function placeButtons()
  476.     local i = 1
  477.     for index,this in pairs(timers) do
  478.         local pausedStatus = ""
  479.         local pausedColor
  480.         local delaySubstitute
  481.         local delayColor = c.delayColorDef
  482.         local msgColor = c.buttonFgDef
  483.         local broadcastAndListenColor = c.buttonFgDef
  484.         local broadcastAndListenOutline = c.buttonOutlineDef
  485.         if this.paused == true then
  486.             pausedStatus = c.pausedText
  487.             pausedColor = c.pausedColor
  488.         else
  489.             if this.msg == "" or this.repeatDelay == math.huge then
  490.                 pausedStatus = c.unpausedText
  491.                 pausedColor = c.unpausedInactiveColor
  492.             else
  493.                 pausedStatus = c.unpausedText
  494.                 pausedColor = c.unpausedColor
  495.             end
  496.         end
  497.         if this.repeatDelay == math.huge then
  498.             delaySubstitute = "INF"
  499.             delayColor = c.delayColorInf
  500.         else
  501.             delaySubstitute = tostring(this.repeatDelay)
  502.         end
  503.         if this.msg == "" then
  504.             broadcastAndListenColor = c.disabledColor
  505.             broadcastAndListenOutline = c.disabledColor
  506.         end
  507.    
  508.        
  509.  
  510.         local delayString = c.delayButtonString .. string.rep(" ",math.floor((unicode.len(c.delayButtonString)/2)-(unicode.len(delaySubstitute)/2))-1) .. delaySubstitute
  511.         delayString = delayString .. string.rep(" ",c.maxwidth_repeatDelay-unicode.len(delayString)-buttonOutlineDefStartLength-buttonOutlineDefEndLength)
  512.  
  513.         local idString = "id: "
  514.  
  515.         if string.len(tostring(this.id)) == 1 then
  516.             idString = idString .. " " .. tostring(this.id)
  517.         else
  518.             idString = idString .. tostring(this.id)
  519.         end
  520.  
  521.         addButton(c.offset_delete,i,c.removeButtonString,c.removeColor,nil,0xFF0000,nil,removeBroadcast,index,c.offset_delete,i)
  522.         addButton(c.offset_listen,i,"listen",broadcastAndListenColor,nil,broadcastAndListenOutline,nil,listen,this.msg)
  523.         addButton(c.offset_paused,i,pausedStatus,pausedColor,nil,pausedColor,nil,switchPauseStatus,index)
  524.         addButton(c.offset_id,i,idString,c.idColor,nil,c.idColor,c.maxwidth_id)
  525.         addButton(c.offset_repeatDelay,i,delayString,delayColor,nil,nil,c.maxwidth_repeatDelay,editDelay,c.offset_repeatDelay,i,index) -- "delay: " .. tostring(this.repeatDelay) also used before to count len
  526.         addButton(c.offset_edit1,i,"chat edit",nil,nil,nil,c.maxwidth_edit1,editMsgThroughChat,c.offset_edit1,i,index)
  527.         addButton(c.offset_broadcast,i,"broadcast",broadcastAndListenColor,nil,broadcastAndListenOutline,nil,buttonBroadcast,index)
  528.         local label = getButtonLabel(index)
  529.         if label == "" then
  530.             msgColor = c.pausedColor
  531.             label = "n/a"
  532.         end
  533.         addButton(c.offset_text,i,label,msgColor,nil,c.buttonOutlineDef,c.maxwidth_text,editMsg,c.offset_text,i,index)
  534.         i = i+1
  535.     end
  536.  
  537.     addButton(1,screenHeight,"+ new broadcast",nil,nil,nil,nil,buttonAddBroadcast)
  538.     addButton(19,screenHeight,"show help",nil,nil,nil,nil,showHelp)
  539.     addButton(31,screenHeight,"reboot",nil,nil,nil,nil,buttonReboot)
  540.     addButton(40,screenHeight,"change name",nil,nil,nil,nil,buttonChangeName,40,screenHeight)
  541. end
  542. function clearButtons()
  543.     buttons = {}
  544. end
  545. function buttonChangeName(x,y)
  546.     gpu.set(x+1,y,string.rep(" ",11))
  547.     term.setCursor(x+1,y)
  548.     local param = {dobreak = false}
  549.     local newName = term.read(param)
  550.     if newName ~= nil and newName ~= "" then
  551.         newName = newName:sub(0,-2)
  552.         newName = newName:gsub("&","§")
  553.  
  554.         if newName:find("§") == nil then
  555.             newName = "§7" .. newName
  556.         end
  557.         name2 = "§8[§eВестник§8]§a " .. newName .. "§f: "
  558.         saveName2()
  559.     end
  560. end
  561.  
  562.  
  563. function pauseAllOnStart()
  564.     for index,this in pairs(timers) do
  565.         if this.paused == false then
  566.             timers[index].paused = true
  567.             timers[index].id = 0
  568.         end
  569.     end
  570. end
  571.  
  572. term.clear()
  573. pauseAllOnStart()
  574. draw(buttons)
  575. while true do
  576.     placeButtons()
  577.     draw()
  578.     getEvent()
  579.     ioSave()
  580.     clearButtons()
  581. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement