Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ----------------------------------------------------
- -- Универсальная многоцелевая программа --
- -- для ручного управления роботом с планшета! --
- -- проект http://computercraft.ru --
- -- 2015, © AlexCC --
- ----------------------------------------------------
- --------------------ROBOT---------------------------
- local robot = require('robot')
- local computer = require('computer')
- local event = require('event')
- local fs = require("filesystem")
- local term = require('term')
- local serial = require('serialization')
- local com = require('component')
- local sides = require('sides')
- local rssignal
- -- Безопасная подгрузка компонентов
- local function safeLoadComponents(name)
- if com.isAvailable(name) then
- return com.getPrimary(name), true
- else
- return 'ERROR! Компонент '..name..' не найден!', false
- end
- end
- -- ===== Всякие принтилки, писалки на экран разной кучи инфы и всякие проверки =====
- -- проверка компонентов
- local tun, state_tun = safeLoadComponents('tunnel')
- local rs, state_redstone = safeLoadComponents('redstone')
- local magnet, state_magnet = safeLoadComponents('tractor_beam')
- local sign, state_sign = safeLoadComponents('sign')
- term.clear()
- print('-------------------------------------------------')
- print(' Универсальная многоцелевая программа ')
- print(' для ручного управления роботом с планшета! ')
- print(' проект http://computercraft.ru ')
- print(' 2015, © AlexCC ')
- print('-------------------------------------------------')
- print('Рекомендуемые аппаратные требования:')
- print('ЦП / ОЗУ: - 3 ур. / 1 Мб')
- print('Сеть: - связанная карта (обязательно)')
- print('Размер инв.: - 16+ слотов')
- print('Апгрейды: - контроллер инвентаря (обязательно)')
- print('магнит, редстоун-карта, апгрейд Табличка I/O')
- print('Опционально: ЧЛ и др. (пока не реализовано)')
- print('-------------------------------------------------')
- term.write('Нажмите ENTER для продолжения...')
- io.read()
- term.clear()
- print('============= Проверка компонентов ===========')
- if not state_tun then
- print (tun)
- print('ВНИМАНИЕ! Аппаратные возможности Вашего робота')
- print('не удовлетворяют миним. требованиям программы!')
- print('Установите в робота тоннельную (связанную) карту для максимально комфортной работы.')
- print('=================================================')
- print ('Программа завершена.')
- os.exit()
- else
- print('Тоннельная карта: ОК ')
- end
- if not state_redstone then
- print (rs)
- print('Аппаратные возможности робота ограничены!')
- print('Вы не сможете управлять редстоун сигналами!')
- rssignal = 'редстоун НЕ УСТ.'
- else
- print('Красная карта: ОК ')
- rssignal = 'редстоун выкл.'
- rs.setOutput(sides.front, 0)
- rs.setOutput(sides.bottom, 0)
- rs.setOutput(sides.top, 0)
- end
- if not state_magnet then
- print(magnet)
- print('Аппаратные возможности робота ограничены!')
- print('Вы не сможете подбирать лут с земли!')
- else
- print('Магнит апгрейд: ОК ')
- end
- if not state_sign then
- print (sign)
- print('Аппаратные возможности робота ограничены!')
- print('Вы не сможете писать на табличках!')
- else
- print('Апгрейд Табличка I/O: ОК ')
- end
- print('=================================================')
- term.write('Нажмите ENTER для продолжения...')
- io.read()
- -- Константы
- local MAXPACKET = tun.maxPacketSize()
- local INVSIZE = robot.inventorySize()
- local MAX_EU = computer.maxEnergy()
- local TOTAL_MEM = computer.totalMemory()/1024
- local neon = {0x0000ff,0x00ff00,0xffff00,0x00ffff,0xff00c0,0xff0000, 0x000000}
- -- Переменные
- local DYNAMIC_VIEW = true
- local current_neon = 1
- local robot_status = 'Ожидаю команд...'
- local function sendData(array)
- local data = serial.serialize(array)
- tun.send(data)
- end
- local function getEU()
- return math.floor(computer.energy())
- end
- local function freeMEM()
- return math.floor(computer.freeMemory()/1024)
- end
- local function printStatus()
- term.clear()
- print('==================== Статус =====================')
- print('Имя робота: '..robot.name())
- print('Уровень прокачки: '..robot.level())
- print('Всего/свободно слотов: '..INVSIZE..'/'..'нет данных')
- print('Ёмкость батареи: '..MAX_EU..' EU')
- print('Текущий заряд: '..getEU()..' EU')
- print('Всего RAM: '..TOTAL_MEM..' KБ')
- print('Свободно RAM: '..freeMEM()..' KБ')
- print('Время работы/RS: '..math.floor(computer.uptime()/60)..' мин./'..rssignal)
- print('=================================================')
- print('Данные Wi-Fi: ', robot_status)
- end
- -- формирование и отправка данных о роботе (параметры, инвентарь и прочее)
- local function infoStatSend()
- local full_info = {
- 'infoRobot',
- 'Имя робота/уровень прокачки: '..robot.name()..'/'..robot.level(),
- 'Всего/свободно слотов: '..INVSIZE..'/нет данных',
- 'Ёмкость батареи/текущий заряд: '..MAX_EU..'/'..getEU()..' EU',
- 'Всего/cвободно RAM: '..TOTAL_MEM..'/'..freeMEM()..' KБ',
- 'Время работы/редстоун: '..math.floor(computer.uptime()/60)..' мин./'..rssignal,
- ' --- Перечень предметов в слотах (слот, имя, кол-во) ---'
- }
- for i=1, INVSIZE do
- local amount = robot.count(i)
- if amount > 0 then
- robot.select(i)
- stack = icontroller.getStackInInternalSlot(i)
- local data_item = i..': '..stack.label..' - '..amount..' шт.'
- table.insert(full_info, data_item)
- end
- end
- sendData(full_info)
- end
- local function infoStatSendDynamicView()
- if DYNAMIC_VIEW == true then infoStatSend() end
- end
- -- ===== таблица действий робота на сетевые команды ======
- local list = {
- --движение робота
- ['w'] = function() robot.forward() end,
- ['s']= function() robot.back() end,
- ['d']= function() robot.turnRight() end,
- ['a']= function() robot.turnLeft() end,
- ['lshift']= function() robot.up() end,
- ['lcontrol']= function() robot.down() end,
- --дейстия сверху ЛКМ, ПКМ, Shift-ПКМ
- ['i']= function() robot.swingUp() end,
- ['o']= function() robot.useUp() end,
- ['p']= function() robot.useUp(sides.top, true) end,
- --дейстия спереди ЛКМ, ПКМ, Shift-ПКМ
- ['q']= function() robot.swing() end,
- ['e']= function() robot.use() end,
- ['r']= function() robot.use(sides.front, true) end,
- --дейстия снизу ЛКМ, ПКМ, Shift-ПКМ
- ['j']= function() robot.swingDown() end,
- ['k']= function() robot.useDown() end,
- ['l']= function() robot.useDown(sides.bottom, true) end,
- --======команды 0-9=================
- --ВЫБРОСИТЬ ВСЕ и выбрать 1-й слот
- ['1']= function()
- for i=1, INVSIZE do
- if robot.count(i) > 0 then
- robot.select(i)
- robot.drop()
- infoStatSendDynamicView()
- end
- end
- robot.select(1)
- end,
- --собрать весь дроп с земли, пока могу это делать!
- ['2']= function()
- if not state_magnet then return end
- robot.select(1)
- while magnet.suck() do
- infoStatSendDynamicView()
- end
- end,
- -- ВЗЯТЬ из сундука СВЕРХУ
- ['3']= function()
- robot.select(1)
- robot.suckUp()
- infoStatSendDynamicView()
- end,
- -- ВЗЯТЬ из сундука СПЕРЕДИ
- ['4']= function()
- robot.select(1)
- robot.suck()
- infoStatSendDynamicView()
- end,
- -- ВЗЯТЬ из сундука СНИЗУ
- ['5']= function()
- robot.select(1)
- robot.suckDown()
- infoStatSendDynamicView()
- end,
- -- Что вокруг меня?
- ['6']= function()
- local scan = {'scan'}
- if robot.detect() then
- table.insert(scan,' Cпереди - БЛОК')
- else
- table.insert(scan,' Cпереди - 0')
- end
- if robot.detectUp() then
- table.insert(scan,' Cверху - БЛОК')
- else
- table.insert(scan,' Cверху - 0')
- end
- if robot.detectDown() then
- table.insert(scan,' Cнизу - БЛОК')
- else
- table.insert(scan,' Cнизу - 0')
- end
- robot.turnRight()
- if robot.detect() then
- table.insert(scan,' Cправа - БЛОК')
- else
- table.insert(scan,' Cправа - 0')
- end
- robot.turnRight()
- if robot.detect() then
- table.insert(scan,' Сзади - БЛОК')
- else
- table.insert(scan,' Сзади - 0')
- end
- robot.turnRight()
- if robot.detect() then
- table.insert(scan,' Слева - БЛОК')
- else
- table.insert(scan,' Слева - 0')
- end
- robot.turnRight()
- sendData(scan)
- end,
- -- Выбрать слот N
- ['7']= function(data) pcall(robot.select, tonumber(data[2])) end,
- --Дроп текущего слота
- ['8']= function() robot.drop() end,
- --показать статистику
- ['9']= function() infoStatSend() end,
- --поставить блок Сверху
- ['z']= function() robot.placeUp() end,
- --поставить блок Спереди
- ['x']= function() robot.place() end,
- --поставить блок Снизу
- ['c']= function() robot.placeDown() end,
- --включить/выключить редстоун излучение
- ['f']= function()
- if not state_redstone then return end
- if rssignal == 'редстоун выкл.' then
- rs.setOutput(sides.front, 15)
- rs.setOutput(sides.bottom, 15)
- rs.setOutput(sides.top, 15)
- rssignal = 'редстоун вкл.'
- else
- rs.setOutput(sides.front, 0)
- rs.setOutput(sides.bottom, 0)
- rs.setOutput(sides.top, 0)
- rssignal = 'редстоун выкл.'
- end
- end,
- --цикличная смена цвета неоновой подсветки робота
- ['n']= function()
- if current_neon > #neon then
- current_neon = 1
- end
- robot.setLightColor(neon[current_neon])
- current_neon = current_neon + 1
- end,
- -- вкл./выкл. показа динамического изменения инвентаря робота
- ['v']= function() DYNAMIC_VIEW = not DYNAMIC_VIEW end,
- --меняем инструмент на инструмент в активном слоте инвентаря
- ['y']= function() if not state_icontroller then return end icontroller.equip() end,
- --пишем текст на табличках
- ['t']= function(data)
- if not state_sign then return end
- sign.setValue(tostring(data[2]))
- end
- }
- local function main()
- robot.select(1)
- printStatus()
- while true do
- --ожидаем команд (события) по wi-fi, каждые 30 сек - срыв ожидания и принт статуса
- e, _, _, _, _, msg = event.pull(30,'modem_message')
- if e then
- robot_status = msg
- printStatus()
- data = serial.unserialize(msg)
- --если существует ключ, вызываем действие из массива и передаем все данные из сообщения
- if list[data[1]] then
- list[data[1]](data)
- end
- else
- -- ничего не делаем, курим, принтим на экран инфу о разряжающейся батарейке:)
- printStatus()
- end
- end
- end
- main()
Add Comment
Please, Sign In to add comment