Hikooshi

cFarmer

Jan 20th, 2021
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 14.73 KB | None | 0 0
  1. local component = require("component")
  2. local gpu = component.gpu
  3. local modem
  4. if component.isAvailable("modem") then modem = component.modem else print("Модем не установлен") end
  5. local term = require("term")
  6. local event = require("event")
  7. local unicode = require("unicode")
  8. local screen = component.screen
  9. local serialization = require("serialization")
  10.  
  11.  
  12.  
  13. local areas = {}
  14. local lists = {main = {x=2, y=6, width=40, height=16, content={}, limit=160, top = false, posF = 1, sb={0x0000FA, true, length=0, shift=0, work=false}, cFore = 0xFAFA00, cBack = 0x222222},
  15.                commands = {x=46, y=6, width=30, height=16, content={}, limit=160, top=true, posF = 1, sb={0x0000FA, true, length=0, shift=0, work=false}, cFore = 0xFAFA00, cBack = 0x222222}}
  16. local modemAddress = "1"
  17. local robotModemAddress = "2"
  18. local messages = {}
  19. local xCursor, yCursor, xCursorMove = 2, 23, 2
  20. local q = 0
  21. local funcs = {}
  22. local port = 384
  23. local cards = {}
  24. local wScreen, hScreen = gpu.maxResolution()
  25. local commandList = {"Команды:",
  26.                      "connect &&&",
  27.                      "Подключиться к роботу",
  28.                      "&&& - первые три символа сетевой карты робота",
  29.                      "    ",
  30.                      "reg cmp|rbt &&&",
  31.                      "Зарегистрировать и записать в файл адреса: cmp - компьютера или rbt - робота; &&& - первые три символа сетевых карт компьютера или робота",
  32.                      "    ",
  33.                      "get cmpt|rbt",
  34.                      "Возвращает адрес сетевой карты компьютера или робота",
  35.                      "    ",
  36.                      "cng feed true|false",
  37.                      "Меняет параметр кормления телят на 'КОРМИТЬ' или 'НЕ КОРМИТЬ'",
  38.                      "    ",
  39.                      "cng time|fdtm|fcnt number",
  40.                      "Меняет настройки: time - время ожидания перед началом фарминга; fdtm - количество пшеницы, которая будет скормлена одному теленку; fcnt - общее количество коров, number - любое числовое значение",
  41.                      "    ",
  42.                      "req nrg|dura|wht|fdtm|fcnt|feed|time",
  43.                      "Запрашивает настройки: nrg - количетсво энергии в роботе; dura - прочность экипированного инструмента; wht - количество оставшейся пшеницы; fdtm - количество пшеницы на одного теленка; fcnt - количество коров; feed - будет кормить телят робот или нет; time - время ожидания перед началом фарминга",
  44.                      "    ",
  45.                      "req slot|iSlot number|all",
  46.                      "Запрашивает данные по слотам: slot - инвентарь, в который перекладывается вся добыча; iSlot - внутренние (internal) слоты, number - чмсло, указывающее определнный слот; all - все слоты",
  47.                      "    ",
  48.                      "exit",
  49.                      "Выход из программы"}
  50. local production = {}
  51. production["Сырая говядина"] = 0
  52. production["Кожа"] = 0
  53.  
  54. local file = io.open("cards", "r")
  55. if file then
  56. local lines = {}
  57.   for line in file:lines() do table.insert(lines, line) end
  58.     for i = 1, #lines do
  59.       for value, value1 in lines[i]:gmatch("(%w+) = (.+)") do
  60.       cards[value] = value1
  61.       end
  62.     end
  63.     modemAddress = cards.cmpt
  64.     robotModemAddress = cards.rbt
  65. file:close()
  66. end
  67.  
  68. if modem then
  69. modem.open(port)
  70. end
  71.  
  72. function add(list, data)
  73.  
  74. local wList = lists[list]
  75. local cPos, shift = 1, wList.width
  76. local totalLines = #wList.content
  77. if data then
  78. local count = math.ceil(unicode.wlen(data) / wList.width)
  79. if totalLines + count > 160 then
  80.   for i = 1, count do
  81.   table.remove(wList.content, 1)
  82.   end
  83. end
  84. --    if totalLines > wList.height then
  85. --    wList.posF = totalLines - wList.height + 1
  86. --    end
  87.       for i = 1, count do
  88.       table.insert(wList.content, unicode.sub(data, cPos, cPos+shift-1))
  89.       cPos = cPos + shift
  90.       end
  91. totalLines = #wList.content
  92.         if totalLines > wList.height and wList.top == false then
  93.         wList.posF = totalLines - wList.height + 1
  94.         end
  95. end
  96. if wList.sb then
  97. local length = 0
  98. local q = 0
  99.   if totalLines > wList.height then
  100.   length = math.floor(wList.height/totalLines*wList.height)
  101.   length = length > 0 and length or 1
  102.   q = (wList.height - 1 - length)/(totalLines - 1 - wList.height)
  103.   q = q > 0 and q or 1
  104.   wList.sb.q = q
  105. --  wList.sb.thumbPosition = math.ceil(math.abs(q*wlist.posF-realLength))
  106.   wList.sb.work = true
  107.   else
  108.   length = wList.height
  109.   q = 0
  110.   end
  111. wList.sb.q = q
  112. wList.sb.thumb = string.rep(" ", length)
  113. end
  114. drawList(lists.main)
  115.  
  116. end
  117.  
  118. function funcs.reg(str)
  119.  
  120. local data = getArgs(str)
  121. local result
  122. local file = io.open("cards", "w")
  123. --for modem in component.list("modem") do
  124. --  if modem ~= modemAddress then
  125. --  robotModemAddress = modem
  126. --  end
  127. --end
  128. --    if robotModemAddress ~= "" then
  129. --    data = "Карта зарегистрирована:".." "..robotModemAddress
  130. --    component.setPrimary("modem", modemAddress)
  131. --    else
  132. --    data = "Карта не зарегистрирована. Вставьте вторую сетевую карту и попробуйте снова"
  133. --    end
  134. if data[1] then
  135.   if data[2] then
  136.     if data[1] == "cmp" then
  137.     modemAddress = component.get(data[2])
  138.       if modemAddress then
  139.       result = "Карта КОМПЬЮТЕРА зарегистрирована:".." "..modemAddress
  140.       cards.cmpt = modemAddress
  141.       else
  142.       result = "Такого модема нет в системе"
  143.       end
  144.     elseif data[1] == "rbt" then
  145.     robotModemAddress = component.get(data[2])
  146.       if robotModemAddress then
  147.         if robotModemAddress == modemAddress then
  148.         result = "Эта карта уже зарегистрирована, как карта КОМПЬЮТЕРА. Введите другой адрес"
  149.         else
  150.         result = "Карта РОБОТА зарегистрирована:".." "..robotModemAddress
  151.         cards.rbt = robotModemAddress
  152.         end
  153.       else
  154.       result = "Такого модема нет в системе"
  155.       end
  156.     else
  157.     result = "Неверная команда"
  158.     end
  159.   else
  160.   result = "Не указан адрес модема или команда введена не верно"
  161.   end
  162. else
  163. result = "Не указаны параметры регистрации"
  164. end
  165.         for k,v in pairs(cards) do
  166.         file:write(k.." = "..v.."\n")
  167.         end
  168. file:close()
  169. add("main", result)
  170. drawList(lists.main)
  171.  
  172. end
  173.  
  174. function drawAreas(area)
  175.  
  176. gpu.setForeground(area.cFore or 0xFFFFFF)
  177. gpu.setBackground(area.cBack or 0x000000)
  178. gpu.fill(area.x, area.y, area.width, area.height, " ")
  179.   if area.sList then
  180.   drawList(area.sList)
  181.   end
  182.     if area.data then
  183.     local firstY = area.y
  184.       for i = 1, #area.data do
  185.       gpu.set(area.x, firstY, area.data[i])
  186.       firstY = firstY + 1
  187.       end
  188.         if area.data.outTbl then
  189.           for k,v in pairs(area.data.outTbl) do
  190.           gpu.set(area.x, firstY, tostring(k) .. " " .. tostring(v))
  191.           firstY = firstY + 1
  192.           end
  193.         end
  194.     end
  195. gpu.setBackground(0x000000)
  196.  
  197. end
  198.  
  199. function drawList(list)
  200.  
  201. gpu.setForeground(list.cFore)
  202. gpu.setBackground(list.cBack)
  203. local allLines = #list.content
  204. --gpu.set(8, 8, tostring(allLines))
  205. --gpu.set(16, 16, tostring(list.sb.shift))
  206. --gpu.set(80, 16, tostring(list.sb.shift))
  207. local linesCount = list.height
  208. gpu.fill(list.x, list.y, list.width, list.height, " ")
  209. --for k,v in pairs(list) do
  210. --  if not list.top then
  211. --    if #list.content > list.height then
  212. --  local fLine = allLines >= linesCount and 1 or math.abs(linesCount - allLines) + 1
  213. --      for i = linesCount, fLine, -1 do
  214. --      gpu.set(list.x, list.y+i-1, list.content[allLines-(linesCount-i)])
  215. --      end    
  216. --    end
  217. --  else
  218. --  local fLine = allLines > linesCount and linesCount or allLines
  219. --    for i = 1, fLine do
  220. --    gpu.set(list.x, list.y+i-1, list.content[i])
  221. --    end
  222. --  end
  223. local shiftF = -1
  224. local fLine = allLines > linesCount and linesCount or allLines
  225.   if not list.top and allLines < linesCount then
  226.   shiftF = linesCount - allLines - 1
  227.   end
  228.     for i = 1, fLine do
  229.     gpu.set(list.x, list.y+i+shiftF, list.content[i+list.posF-1])
  230.     end
  231.       if list.sb then
  232.       gpu.setBackground(0x000044)
  233.       gpu.fill(list.x+list.width, list.y, 1, list.height, " ")
  234.       gpu.setBackground(list.sb[1])
  235.       local thumbPosition = math.ceil(list.sb.q*(list.posF-1))
  236.       gpu.set(list.x+list.width, list.y+thumbPosition, list.sb.thumb, list.sb[2])
  237.       end
  238. --end
  239. gpu.setForeground(0xFAFA00)
  240. gpu.setBackground(0x222222)
  241.  
  242. end
  243.  
  244. --local funcs = {reg = regCard}
  245.  
  246. function funcs.connect(str)
  247.  
  248. local result = ""
  249. local addr = getArgs(str)
  250. if modemAddress ~= "1" and robotModemAddress ~= "2" and modemAddress and robotModemAddress then
  251.   if addr[1] ~= nil then
  252.   modem.send(robotModemAddress, port, "connect".." "..addr[1])
  253.   local _,_,_,_,_,message = event.pull(2, "modem_message", modemAddress, robotModemAddress)
  254.     if message == nil then
  255.     result = "Не удалось подключиться к роботу"
  256.     else
  257.     result = message
  258.     end
  259.   else
  260.   result = "Укажите адрес, к которому хотите подключиться"
  261.   end
  262. else
  263. result = "Модем компьютера или робота не зарегистрирован"
  264. end
  265. add("main", result)
  266.  
  267. end
  268.  
  269. function getTableLength(tbl)
  270.  
  271. local length = 0
  272. for k,v in pairs(tbl) do
  273.   if k then length = length + 1 end
  274. end
  275. return length
  276.  
  277. end
  278.  
  279. function funcs.get(str)
  280.  
  281. local cName = getArgs(str)
  282. local result = ""
  283. if getTableLength(cards) > 0 then
  284.   if cards[cName[1]] then
  285.   result = cards[cName[1]]
  286.   else
  287.   result = "Компонент не указан или его нет в списке"
  288.   end
  289. else
  290. result = "Зарегистрированы не все модемы"
  291. end
  292. add("main", result)
  293.  
  294. end
  295.  
  296. function funcs.cng(str)
  297.  
  298. local result = ""
  299. local parameters = getArgs(str)
  300. modem.send(robotModemAddress, port, "cng", parameters[1], parameters[2])
  301. local _,_,_,_,_,message = event.pull(2, "modem_message", modemAddress, robotModemAddress)
  302.   if not message then
  303.   result = "Нет связи с роботом"
  304.   else
  305.   result = "Robot: "..message
  306.   end
  307. add("main", result)
  308.  
  309. end
  310.  
  311. function funcs.req(str)
  312.  
  313. local result = ""
  314. local parameters = getArgs(str)
  315. modem.send(robotModemAddress, port, "req", parameters[1], parameters[2])
  316. local _,_,_,_,_,message = event.pull(20, "modem_message", modemAddress, robotModemAddress)
  317.   if not message then
  318.   result = "Нет связи с роботом"
  319.   else
  320.   result = "Robot: "..message
  321.   end
  322. add("main", result)
  323.  
  324. end
  325.  
  326. gpu.setResolution(80, 25)
  327. gpu.setBackground(0x444444)
  328. term.clear()
  329.  
  330. table.insert(areas, {x=lists.main.x, y=lists.main.y, width=lists.main.width, height=lists.main.height, sList=lists.main, cBack = lists.main.cBack})
  331. table.insert(areas, {x=lists.commands.x, y=lists.commands.y, width=lists.commands.width, height=lists.commands.height, sList=lists.commands, cBack = lists.commands.cBack})
  332. table.insert(areas, {x=2, y=2, width=40, height=3, data={"Добыча:", outTbl = production}, cFore = 0xFFFFFF, cBack = 0x222222})
  333. add("main")
  334. for i = 1, #commandList do
  335. add("commands", commandList[i])
  336. end
  337.  
  338. for k,v in pairs(areas) do
  339. drawAreas(v)
  340. end
  341. gpu.setForeground(0xFAFA00)
  342. gpu.setBackground(0x222222)
  343. gpu.fill(xCursor, yCursor, lists.main.width, 1, " ")
  344. term.setCursor(xCursor, yCursor)
  345. local str = ""
  346.  
  347. function getArgs(data)
  348.  
  349. local gArgs = {}
  350. for arg in data:gmatch("%S+") do table.insert(gArgs, arg) end
  351. table.remove(gArgs, 1)
  352. return gArgs
  353.  
  354. end
  355.  
  356. function funcs.exit()
  357.  
  358. gpu.setForeground(0xFFFFFF)
  359. gpu.setBackground(0x000000)
  360. term.clear()
  361. gpu.setResolution(wScreen, hScreen)
  362. os.exit()
  363.  
  364. end
  365.  
  366. --print(modemAddress, robotModemAddress)
  367.  
  368. while true do
  369. --local termData = term.read(_, false):match("[^\n]+")
  370. --add("main", termData)
  371. --drawList(lists.main)
  372. --gpu.fill(xCursor, yCursor, 40, 1, " ")
  373. --term.setCursor(xCursor, yCursor)
  374. local event, address, char, port, distance, message, message1 = term.pull()
  375.   if event == "key_down" then
  376.   local addition = unicode.char(char):match("[^%c]") or ""
  377.   str = str .. addition
  378.   local newStr = unicode.sub(str, -40, unicode.wlen(str))
  379.   gpu.set(xCursor, yCursor, newStr)
  380.   xCursorMove = xCursorMove + (xCursorMove - xCursor < 40 and unicode.wlen(addition) or 0)
  381.   term.setCursor(xCursorMove, yCursor)
  382.     if char == 13 then
  383. --      local fnc = str:match("%w+")
  384. --      if funcs[fnc] then funcs[fnc]() end
  385.     add("main", str)
  386.     drawList(lists.main)
  387.     gpu.setForeground(0xFAFA00)
  388.     gpu.setBackground(0x222222)
  389.     gpu.fill(xCursor, yCursor, 40, 1, " ")
  390.     xCursorMove = xCursor
  391.     term.setCursor(xCursor, yCursor)
  392.       local fnc = str:match("%w+")
  393.       if funcs[fnc] then funcs[fnc](str) end
  394.     str = ""
  395.     elseif char == 8 then
  396.     str = unicode.wtrunc(str, unicode.wlen(str))
  397.     gpu.fill(xCursor, yCursor, 40, 1, " ")
  398.     gpu.set(xCursor, yCursor, str)
  399.     xCursorMove = xCursorMove - (xCursorMove > xCursor and 1 or 0)
  400.     term.setCursor(xCursorMove, yCursor)
  401.     end
  402.   elseif event == "modem_message" and char == robotModemAddress then
  403.   add("main", "Robot: "..message)
  404.     if message1 then
  405.     local prod = serialization.unserialize(message1)
  406.     add("main", "Robot: добыча на этот раз:")
  407.       for name, count in pairs(prod) do
  408.         add("main", name .. " " .. tostring(count))
  409.           if production[name] then
  410.           production[name] = production[name] + count
  411. --          else
  412. --          production[name] = count
  413.           end
  414.       end
  415.     drawAreas(areas[3])
  416.     end
  417.   elseif event == "scroll" then
  418.   local lst = false
  419.     for k,v in pairs(areas) do
  420.       if char >= v.x and char < v.x+v.width and port >= v.y and port < v.y+v.height and v.sList then
  421.       lst = v.sList
  422.       break
  423.       end
  424.     end
  425.         if lst and lst.sb.work then
  426.           if lst.content[(lst.posF - distance) + ((lst.height - 1) * ((1-distance)/2))] then
  427.           lst.posF = lst.posF - distance
  428.           end
  429.           drawList(lst)
  430.         end
  431.   end
  432. end
Add Comment
Please, Sign In to add comment