Advertisement
Guest User

q.lua

a guest
Nov 20th, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 8.80 KB | None | 0 0
  1. local component = require("component")
  2. local term = require("term")
  3. local shell = require("shell")
  4. local fs = require("filesystem")
  5. local computer = require("computer")
  6. local chat = component.chat_box
  7. local internet = require('internet')
  8. local event = require('event')
  9. _G.imodem = {}
  10. local server = 'irc.esper.net:6667'
  11. local nick = "Message"
  12. imodem.channel = "#message"
  13. local on_exit = 1
  14. local con = 1
  15. local ex = require("term")
  16. cloak = "выключена"
  17. local rad = component.radar
  18. pl = rad.getPlayers()
  19. local online = computer.addUser
  20. local gpu = component.gpu
  21. local c = require('serialization')
  22. local players = {}
  23. local det = computer.addUser
  24. local roc = component.tile_defense_machine_launcherscreen_name
  25.  
  26.  
  27. function check(pmsg)
  28.   while true do
  29.     mssg = {}
  30.     local find = string.find(pmsg," ")
  31.     local i = 1
  32.     while true do     --сканим все фуфло
  33.       if find == nil then
  34.         mssg[i] = pmsg
  35.         print("конец текста")
  36.         comm()
  37.         break
  38.       else
  39.         mssg[i] = string.sub(pmsg,1,find-1)
  40.         pmsg = string.sub(pmsg,find+1)
  41.         find = string.find(pmsg," ")
  42.         i = i+1
  43.         --print("финды "..find)
  44.         --print("текст "..mssg[i])
  45.         --print("остаток "..pmsg)        
  46.       end
  47.     end
  48. break
  49.       --print(comm)
  50.   end
  51.   os.sleep(1)
  52. end
  53.  
  54. function comm()
  55.   if mssg[1] == "!rtarget" then
  56.     if mssg[2] == "жива?" then
  57.       chat.say("Да")
  58.     else
  59.       local x = mssg[2]
  60.       local y = mssg[3]
  61.       local z = mssg[4]
  62.       local x = tonumber(x)
  63.       local y = tonumber(y)
  64.       local z = tonumber(z)
  65.       roc.setTarget(x, y, z)
  66.     end
  67.   end
  68. end
  69.  
  70.  
  71.  
  72.  
  73.  
  74. function AddManually(rply)--ручное добавление ника в базу
  75. AddPlayerToBD(rply)
  76. end
  77.  
  78.  function detectOnline()--тут проверяем онлайн. Если игрок таки онлайн - отправляем через туннельную карту его ник
  79. non = 0
  80.   for j = 1, #players do
  81.     names=players[j]
  82.     prov=det(names)
  83.     if prov ~= nil then imodem.broadcast("Игрок: "..names.." ONL") non = non + 1 end--тут отправляем ник
  84.     if names == "Domenk" then
  85. iws = 1
  86.     else
  87.     computer.removeUser(names)
  88.     end
  89.   end
  90. imodem.broadcast("Общий онлайн: "..non..".")
  91. end
  92.  
  93.  
  94. function readBD()--чтение базы данных в массив (один раз, при запуске программы. В дальнейшем работаем с массивом)
  95.   local d=1
  96.       local f = io.open("Players.txt","r")
  97. f:seek("set",0);
  98.     for line in f:lines() do
  99.       players[d]=line
  100.       d=d+1
  101.  
  102.     end
  103.        f:close()
  104.  
  105. end
  106.  
  107.  
  108.  
  109.  
  110. function AddPlayerToBD(addply)--проверка ника и если его нет в базе данных - добавляем
  111.   local flstr=2
  112.        for j = 1, #players do
  113.           if players[j]==addply then flstr=1 break end--игрок уже есть в БД, меняем переменную-флаг и прерываем цикл
  114.       end
  115.        
  116.     if flstr == 2 then
  117.       f = io.open("Players.txt","a");
  118.       f:write(addply.."\n")
  119.       --записали нового игрока в БД
  120.       f:flush()
  121.       f:close()
  122.       --добавляем имя игрока в массив
  123.       local mass = #players+1
  124.       players[mass]=addply
  125.     end
  126.      
  127.  
  128. end
  129.  
  130.  
  131. function name(identity)--не знаю для чего она :)
  132.   return identity and identity:match('^[^!]+') or identity or 'Anonymous'
  133. end
  134.  
  135. function chat_(nick,message)--чат
  136. check(message)
  137. if message == "!o"
  138. then
  139. detectOnline()
  140. else
  141. if message == "!help"
  142. then
  143. imodem.broadcast("Доступные команды:")
  144. imodem.broadcast("Онлайн сервера !o")
  145. imodem.broadcast("Невидимость корабля: !io ; !if")
  146. imodem.broadcast("Вся доступная информация: !status")
  147. else
  148. if message == "!status"
  149. then
  150. imodem.broadcast("Невидимость:" .. cloak .. ".")
  151. if pl[1] then
  152. imodem.broadcast("Игрок" .. pl[1]["name"] .. ".")
  153. if pl[2] then
  154. imodem.broadcast("Игрок" .. pl[2]["name"] .. ".")
  155. if pl[3] then
  156. imodem.broadcast("Игрок" .. pl[3]["name"] .. ".")
  157. if pl[4] then
  158. imodem.broadcast("Игрок" .. pl[4]["name"] .. ".")
  159. if pl[5] then
  160. imodem.broadcast("Игрок" .. pl[5]["name"] .. ".")
  161. end
  162. end
  163. end
  164. end
  165. end
  166. else
  167. if message == "!io"
  168. then
  169. component.tunnel.send("on")
  170. cloak = "Включена"
  171. imodem.broadcast("Невидимость корабля активирована.")
  172. else
  173. if message == "!if"
  174. then
  175. component.tunnel.send("off")
  176. cloak = "Выключена"
  177. imodem.broadcast("Невидимость корабля деактивирована.")
  178. else
  179. if message == "ня пока"
  180. then
  181. on_exit = 0
  182. imodem.stop()
  183. return
  184. else
  185. if nick == "DOMENK" then
  186. chat.setName(nick)
  187. term.clear()
  188. chat.say(message)
  189. print(message)
  190. else
  191. imodem.broadcast("Чужакам тут не место, уходи.")
  192. end
  193. end
  194. end
  195. end
  196. end
  197. end
  198. end
  199. end
  200. function imodem.broadcast(message)--функция отправки сообщений на IRC сервер
  201.   if sock and imodem.channel then
  202.     sock:write("PRIVMSG " .. imodem.channel .. " :" .. message..'\r\n')
  203.      sock:flush()
  204.     return true
  205.   else
  206. con = 0
  207. connect(0)
  208. return false
  209.   end
  210. end
  211.  
  212.  
  213.   function imodem.stop()--отключение от IRC сервера
  214.   if imodem.timer then
  215.     if sock then
  216.       sock:write('QUIT\r\n')
  217.       sock:close()
  218.     end
  219.     event.cancel(imodem.timer)
  220.   end
  221. end
  222.  
  223.  
  224. function connect(flag)--по сути главная функция. Отвечает за соединение с IRC сервером, за прием сообщений от него, за проверку и поддержание соединения
  225. if con == 0 and flag == 0 then
  226. sock, reason = internet.open(server)
  227. sock:setTimeout(0.05)
  228. sock:write('NICK '..nick..'\r\n')
  229. sock:write('USER '..nick..' 0 * :'..nick..'\r\n')
  230. sock:flush()
  231. if not sock then
  232.   io.stderr:write(reason..'\n')
  233.   return
  234. end
  235. end
  236.  
  237. imodem.timer = event.timer(0.5, function()
  238.  
  239.   if not sock then return false end
  240.   repeat
  241.    ok, line = pcall(sock.read, sock)
  242.     if ok then
  243.       if not line then
  244.         sock:close()
  245.         sock = nil
  246.       end
  247.       match, prefix = line:match('^(:(%S+) )')
  248.       if match then line = line:sub(#match+1) end
  249.       local match, command = line:match('^(([^:]%S*))')
  250.       if match then line = line:sub(#match+1) end
  251.      args = {}
  252.       repeat
  253.       match, arg = line:match('^( ([^:]%S*))')
  254.         if match then
  255.           line = line:sub(#match+1)
  256.           table.insert(args, arg)
  257.         end
  258.       until not match
  259.      local message = line:match('^ :(.*)$')
  260. term.clear()
  261. print (command)
  262.       if command == '004' then
  263.         sock:write('JOIN '..imodem.channel..' nbgjhjvbr'..'\r\n')
  264.         sock:flush()
  265. con = 1
  266.       elseif command == 'PING' then
  267.         sock:write('PONG :'..message..'\r\n')
  268.         sock:flush()
  269.       elseif command == 'PRIVMSG' then
  270.         computer.pushSignal('modem_message', nick, name(prefix), 0, 0, message)
  271. print(message)--именно здесь принимаются сообщения от IRC!!
  272. --function(message) Вот так сюда можно вставить функцию, которая будет принимать и обрабатывать сообщение (message) от IRC
  273. chat_(name(prefix), message)      
  274. end
  275.     end
  276.   until not ok
  277.  
  278. end, math.huge)
  279. end
  280.  
  281. function sendsms (player, message)--обработка сообщения от чата или других событий в игре и пересылка его в функцию отправки на IRC сервер
  282. if player ~= "Ашшарх" and player ~= "Гросс" and player ~= "Евпсихий" and player ~= "Прашнартра" and player ~= "Киппс" and player ~= "Джейк Риденс" and player ~= "Пришелец" and player ~= "ИнопланеТЯНКА" then
  283. AddPlayerToBD(player)
  284. check(message)
  285. imodem.broadcast(player..": "..message)
  286. --term.clear()
  287. print(message)
  288. end
  289. end
  290.  
  291. --++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  292.  
  293.  
  294. connect(0)
  295. readBD()
  296.  
  297. while on_exit == 1 do--главный цикл. И этим все сказано.
  298. local e = { computer.pullSignal(2) }
  299. if not sock and con == 1 then
  300. con = 0
  301. event.push ("soedinit")
  302. connect(0)
  303. end
  304.  
  305. if e[1] == "modem_message"  then
  306. if e[10] == "RLO" then--пример того, как можно принять управляющий флаг от тоннельной карты
  307. imodem.broadcast(e[9])-- и передать некое сообщение находяшееся в поле e[9] в IRC
  308. end
  309.  
  310. elseif e[1] == "chat_message" then
  311. sendsms(e[3], e[4])
  312.  
  313. elseif e[1] == "key_down" then --дальше идут клавиши управления. Выключение проги или же просто дисконнект IRC
  314.  
  315. if e[4] == 16 then --выход из проги
  316. term.clear()
  317. on_exit = 0
  318.  
  319. elseif e[4] == 24 then--дисконнект
  320. imodem.stop()
  321.  
  322. end
  323. end
  324. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement