Darkar25

1

Jun 18th, 2017
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.82 KB | None | 0 0
  1. ----------------------------------------------------
  2. -- Универсальная многоцелевая программа --
  3. -- для ручного управления роботом с планшета! --
  4. -- проект http://computercraft.ru --
  5. -- 2015, © AlexCC --
  6. ----------------------------------------------------
  7. --------------------ROBOT---------------------------
  8.  
  9.  
  10. local robot = require('robot')
  11. local computer = require('computer')
  12. local event = require('event')
  13. local fs = require("filesystem")
  14. local term = require('term')
  15. local serial = require('serialization')
  16. local com = require('component')
  17. local sides = require('sides')
  18. local rssignal
  19.  
  20. -- Безопасная подгрузка компонентов
  21. local function safeLoadComponents(name)
  22. if com.isAvailable(name) then
  23. return com.getPrimary(name), true
  24. else
  25. return 'ERROR! Компонент '..name..' не найден!', false
  26. end
  27. end
  28.  
  29. -- ===== Всякие принтилки, писалки на экран разной кучи инфы и всякие проверки =====
  30.  
  31. -- проверка компонентов
  32. local tun, state_tun = safeLoadComponents('tunnel')
  33. local rs, state_redstone = safeLoadComponents('redstone')
  34. local magnet, state_magnet = safeLoadComponents('tractor_beam')
  35. local sign, state_sign = safeLoadComponents('sign')
  36.  
  37. term.clear()
  38. print('-------------------------------------------------')
  39. print(' Универсальная многоцелевая программа ')
  40. print(' для ручного управления роботом с планшета! ')
  41. print(' проект http://computercraft.ru ')
  42. print(' 2015, © AlexCC ')
  43. print('-------------------------------------------------')
  44. print('Рекомендуемые аппаратные требования:')
  45. print('ЦП / ОЗУ: - 3 ур. / 1 Мб')
  46. print('Сеть: - связанная карта (обязательно)')
  47. print('Размер инв.: - 16+ слотов')
  48. print('Апгрейды: - контроллер инвентаря (обязательно)')
  49. print('магнит, редстоун-карта, апгрейд Табличка I/O')
  50. print('Опционально: ЧЛ и др. (пока не реализовано)')
  51. print('-------------------------------------------------')
  52. term.write('Нажмите ENTER для продолжения...')
  53. io.read()
  54. term.clear()
  55. print('============= Проверка компонентов ===========')
  56. if not state_tun then
  57. print (tun)
  58. print('ВНИМАНИЕ! Аппаратные возможности Вашего робота')
  59. print('не удовлетворяют миним. требованиям программы!')
  60. print('Установите в робота тоннельную (связанную) карту для максимально комфортной работы.')
  61. print('=================================================')
  62. print ('Программа завершена.')
  63. os.exit()
  64. else
  65. print('Тоннельная карта: ОК ')
  66. end
  67. if not state_redstone then
  68. print (rs)
  69. print('Аппаратные возможности робота ограничены!')
  70. print('Вы не сможете управлять редстоун сигналами!')
  71. rssignal = 'редстоун НЕ УСТ.'
  72. else
  73. print('Красная карта: ОК ')
  74. rssignal = 'редстоун выкл.'
  75. rs.setOutput(sides.front, 0)
  76. rs.setOutput(sides.bottom, 0)
  77. rs.setOutput(sides.top, 0)
  78. end
  79. if not state_magnet then
  80. print(magnet)
  81. print('Аппаратные возможности робота ограничены!')
  82. print('Вы не сможете подбирать лут с земли!')
  83. else
  84. print('Магнит апгрейд: ОК ')
  85. end
  86. if not state_sign then
  87. print (sign)
  88. print('Аппаратные возможности робота ограничены!')
  89. print('Вы не сможете писать на табличках!')
  90. else
  91. print('Апгрейд Табличка I/O: ОК ')
  92. end
  93. print('=================================================')
  94. term.write('Нажмите ENTER для продолжения...')
  95. io.read()
  96.  
  97.  
  98. -- Константы
  99. local MAXPACKET = tun.maxPacketSize()
  100. local INVSIZE = robot.inventorySize()
  101. local MAX_EU = computer.maxEnergy()
  102. local TOTAL_MEM = computer.totalMemory()/1024
  103. local neon = {0x0000ff,0x00ff00,0xffff00,0x00ffff,0xff00c0,0xff0000, 0x000000}
  104.  
  105. -- Переменные
  106. local DYNAMIC_VIEW = true
  107. local current_neon = 1
  108. local robot_status = 'Ожидаю команд...'
  109.  
  110. local function sendData(array)
  111. local data = serial.serialize(array)
  112. tun.send(data)
  113. end
  114.  
  115. local function getEU()
  116. return math.floor(computer.energy())
  117. end
  118.  
  119. local function freeMEM()
  120. return math.floor(computer.freeMemory()/1024)
  121. end
  122.  
  123. local function printStatus()
  124. term.clear()
  125. print('==================== Статус =====================')
  126. print('Имя робота: '..robot.name())
  127. print('Уровень прокачки: '..robot.level())
  128. print('Всего/свободно слотов: '..INVSIZE..'/'..'нет данных')
  129. print('Ёмкость батареи: '..MAX_EU..' EU')
  130. print('Текущий заряд: '..getEU()..' EU')
  131. print('Всего RAM: '..TOTAL_MEM..' KБ')
  132. print('Свободно RAM: '..freeMEM()..' KБ')
  133. print('Время работы/RS: '..math.floor(computer.uptime()/60)..' мин./'..rssignal)
  134. print('=================================================')
  135. print('Данные Wi-Fi: ', robot_status)
  136. end
  137. -- формирование и отправка данных о роботе (параметры, инвентарь и прочее)
  138. local function infoStatSend()
  139. local full_info = {
  140. 'infoRobot',
  141. 'Имя робота/уровень прокачки: '..robot.name()..'/'..robot.level(),
  142. 'Всего/свободно слотов: '..INVSIZE..'/нет данных',
  143. 'Ёмкость батареи/текущий заряд: '..MAX_EU..'/'..getEU()..' EU',
  144. 'Всего/cвободно RAM: '..TOTAL_MEM..'/'..freeMEM()..' KБ',
  145. 'Время работы/редстоун: '..math.floor(computer.uptime()/60)..' мин./'..rssignal,
  146. ' --- Перечень предметов в слотах (слот, имя, кол-во) ---'
  147. }
  148. for i=1, INVSIZE do
  149. local amount = robot.count(i)
  150. if amount > 0 then
  151. robot.select(i)
  152. stack = icontroller.getStackInInternalSlot(i)
  153. local data_item = i..': '..stack.label..' - '..amount..' шт.'
  154. table.insert(full_info, data_item)
  155. end
  156. end
  157. sendData(full_info)
  158. end
  159.  
  160. local function infoStatSendDynamicView()
  161. if DYNAMIC_VIEW == true then infoStatSend() end
  162. end
  163.  
  164. -- ===== таблица действий робота на сетевые команды ======
  165. local list = {
  166.  
  167. --движение робота
  168. ['w'] = function() robot.forward() end,
  169. ['s']= function() robot.back() end,
  170. ['d']= function() robot.turnRight() end,
  171. ['a']= function() robot.turnLeft() end,
  172. ['lshift']= function() robot.up() end,
  173. ['lcontrol']= function() robot.down() end,
  174.  
  175. --дейстия сверху ЛКМ, ПКМ, Shift-ПКМ
  176. ['i']= function() robot.swingUp() end,
  177. ['o']= function() robot.useUp() end,
  178. ['p']= function() robot.useUp(sides.top, true) end,
  179.  
  180. --дейстия спереди ЛКМ, ПКМ, Shift-ПКМ
  181. ['q']= function() robot.swing() end,
  182. ['e']= function() robot.use() end,
  183. ['r']= function() robot.use(sides.front, true) end,
  184.  
  185. --дейстия снизу ЛКМ, ПКМ, Shift-ПКМ
  186. ['j']= function() robot.swingDown() end,
  187. ['k']= function() robot.useDown() end,
  188. ['l']= function() robot.useDown(sides.bottom, true) end,
  189.  
  190. --======команды 0-9=================
  191. --ВЫБРОСИТЬ ВСЕ и выбрать 1-й слот
  192. ['1']= function()
  193. for i=1, INVSIZE do
  194. if robot.count(i) > 0 then
  195. robot.select(i)
  196. robot.drop()
  197. infoStatSendDynamicView()
  198. end
  199. end
  200. robot.select(1)
  201. end,
  202.  
  203. --собрать весь дроп с земли, пока могу это делать!
  204. ['2']= function()
  205. if not state_magnet then return end
  206. robot.select(1)
  207. while magnet.suck() do
  208. infoStatSendDynamicView()
  209. end
  210. end,
  211.  
  212. -- ВЗЯТЬ из сундука СВЕРХУ
  213. ['3']= function()
  214. robot.select(1)
  215. robot.suckUp()
  216. infoStatSendDynamicView()
  217. end,
  218.  
  219. -- ВЗЯТЬ из сундука СПЕРЕДИ
  220. ['4']= function()
  221. robot.select(1)
  222. robot.suck()
  223. infoStatSendDynamicView()
  224. end,
  225.  
  226. -- ВЗЯТЬ из сундука СНИЗУ
  227. ['5']= function()
  228. robot.select(1)
  229. robot.suckDown()
  230. infoStatSendDynamicView()
  231. end,
  232.  
  233. -- Что вокруг меня?
  234. ['6']= function()
  235. local scan = {'scan'}
  236. if robot.detect() then
  237. table.insert(scan,' Cпереди - БЛОК')
  238. else
  239. table.insert(scan,' Cпереди - 0')
  240. end
  241. if robot.detectUp() then
  242. table.insert(scan,' Cверху - БЛОК')
  243. else
  244. table.insert(scan,' Cверху - 0')
  245. end
  246. if robot.detectDown() then
  247. table.insert(scan,' Cнизу - БЛОК')
  248. else
  249. table.insert(scan,' Cнизу - 0')
  250. end
  251. robot.turnRight()
  252. if robot.detect() then
  253. table.insert(scan,' Cправа - БЛОК')
  254. else
  255. table.insert(scan,' Cправа - 0')
  256. end
  257. robot.turnRight()
  258. if robot.detect() then
  259. table.insert(scan,' Сзади - БЛОК')
  260. else
  261. table.insert(scan,' Сзади - 0')
  262. end
  263. robot.turnRight()
  264. if robot.detect() then
  265. table.insert(scan,' Слева - БЛОК')
  266. else
  267. table.insert(scan,' Слева - 0')
  268. end
  269. robot.turnRight()
  270. sendData(scan)
  271. end,
  272.  
  273. -- Выбрать слот N
  274. ['7']= function(data) pcall(robot.select, tonumber(data[2])) end,
  275.  
  276. --Дроп текущего слота
  277. ['8']= function() robot.drop() end,
  278.  
  279. --показать статистику
  280. ['9']= function() infoStatSend() end,
  281.  
  282. --поставить блок Сверху
  283. ['z']= function() robot.placeUp() end,
  284.  
  285. --поставить блок Спереди
  286. ['x']= function() robot.place() end,
  287.  
  288. --поставить блок Снизу
  289. ['c']= function() robot.placeDown() end,
  290.  
  291. --включить/выключить редстоун излучение
  292. ['f']= function()
  293. if not state_redstone then return end
  294. if rssignal == 'редстоун выкл.' then
  295. rs.setOutput(sides.front, 15)
  296. rs.setOutput(sides.bottom, 15)
  297. rs.setOutput(sides.top, 15)
  298. rssignal = 'редстоун вкл.'
  299. else
  300. rs.setOutput(sides.front, 0)
  301. rs.setOutput(sides.bottom, 0)
  302. rs.setOutput(sides.top, 0)
  303. rssignal = 'редстоун выкл.'
  304. end
  305. end,
  306. --цикличная смена цвета неоновой подсветки робота
  307. ['n']= function()
  308. if current_neon > #neon then
  309. current_neon = 1
  310. end
  311. robot.setLightColor(neon[current_neon])
  312. current_neon = current_neon + 1
  313. end,
  314.  
  315. -- вкл./выкл. показа динамического изменения инвентаря робота
  316. ['v']= function() DYNAMIC_VIEW = not DYNAMIC_VIEW end,
  317.  
  318. --меняем инструмент на инструмент в активном слоте инвентаря
  319. ['y']= function() if not state_icontroller then return end icontroller.equip() end,
  320.  
  321. --пишем текст на табличках
  322. ['t']= function(data)
  323. if not state_sign then return end
  324. sign.setValue(tostring(data[2]))
  325. end
  326.  
  327. }
  328.  
  329.  
  330. local function main()
  331. robot.select(1)
  332. printStatus()
  333. while true do
  334. --ожидаем команд (события) по wi-fi, каждые 30 сек - срыв ожидания и принт статуса
  335. e, _, _, _, _, msg = event.pull(30,'modem_message')
  336. if e then
  337. robot_status = msg
  338. printStatus()
  339. data = serial.unserialize(msg)
  340. --если существует ключ, вызываем действие из массива и передаем все данные из сообщения
  341. if list[data[1]] then
  342. list[data[1]](data)
  343. end
  344. else
  345. -- ничего не делаем, курим, принтим на экран инфу о разряжающейся батарейке:)
  346. printStatus()
  347. end
  348. end
  349. end
  350.  
  351. main()
Add Comment
Please, Sign In to add comment