Asioron

Untitled

Feb 28th, 2017
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 34.04 KB | None | 0 0
  1. ---------------------------------------------------------
  2. -- Программа --
  3. -- для автоматической ловли рыбы или хлама в Майнкрафт --
  4. -- на роботе из мода OpenComputers --
  5. -- Роборыболов v0.1 --
  6. -- проект http://computercraft.ru --
  7. -- 2016, © Asior --
  8. ---------------------------------------------------------
  9.  
  10. ----------------БИБЛИОТЕКИ-------------------
  11. local event = require("event")
  12. local r = require('robot')
  13. local computer = require("computer")
  14. local unicode = require("unicode")
  15. local fl = require("filesystem")
  16. local gpu = require("component").gpu
  17. local term = require("term")
  18. --------------ПРОЦЕДУРЫ----------------------
  19.  
  20. local function toboolean(string)
  21. return string == "true"
  22. end
  23.  
  24. local function Settings(repetition) --загрузка или перезапись настроек в файл
  25. if repetition then fl.remove("../etc/Ribolov.cnf") end
  26. local file = io.open("../etc/Ribolov.cnf", "r")
  27. if file == nil then
  28. file = io.open("../etc/Ribolov.cnf", "w")
  29. file:write('fishing = '..tostring(setting[1])..'\ndrop = '..tostring(setting[2])..'\ndoSearch = '..tostring(setting[3])..'\ncraft = '..tostring(setting[4])..'\ndoRepair = '..tostring(setting[5])..'\n')
  30. for i = 1, #black_list do
  31. file:write('bl = '..black_list[i]..'\n')
  32. end
  33. else
  34. local line = file:read()
  35. while line do
  36. local arg = string.sub(line, 1, string.find(line, '=')-2)
  37. --print(arg)os.sleep(0.3)
  38. if arg == 'fishing' then setting[1] = string.sub(line, #arg+4)
  39. elseif arg == 'drop' then setting[2] = string.sub(line, #arg+4)
  40. elseif arg == 'doSearch' then setting[3] = string.sub(line, #arg+4)--поиск
  41. elseif arg == 'craft' then setting[4] = toboolean(string.sub(line, #arg+4))
  42. elseif arg == 'doRepair' then setting[5] = toboolean(string.sub(line, #arg+4))--ремонт doRepair
  43. elseif arg == 'bl' then black_list[#black_list+1] = string.sub(line, #arg+4)
  44. end
  45. line = file:read()
  46. end
  47. end
  48. file:close()
  49. if not Tsetting[2] then --если нету контроллера
  50. setting[3] = false
  51. end
  52. if not (Tsetting[2] and Tsetting[1]) then --если нету контроллера и верстака
  53. setting[4] = false
  54. setting[5] = false
  55. end
  56. end
  57.  
  58. local function componentTesting() --тестирвание и начальная настройка компонентов
  59. --крафтовый стол, контроллер инвентаря, буфер
  60. term.clear()
  61. print('Проверка компонентов робота, подождите...')
  62. if require("component").isAvailable("redstone") then
  63. redstone = require("component").redstone
  64. print('Плата красного камня успешно подключена')
  65. else
  66. print("Плата красного камня не обнаружена!\nВы забыли установить плату красного камня, работа без неё невозможна, установите отсутствующее устройство и перезагрузите программу")
  67. os.exit()
  68. end
  69. Tsetting[3] = r.inventorySize()
  70. if Tsetting[3] == 0 then
  71. print("Нету инвентаря!\nУстановите апгрейд инвентаря и перезагрузите программу")
  72. os.exit()
  73. else
  74. print("Инвентарь в размере "..Tsetting[3].." слотов обнаружен")
  75. os.sleep(0.1)
  76. end
  77. if require("component").isAvailable("inventory_controller") then
  78. incontrol = require("component").inventory_controller
  79. print('Контроллер успешно подключен')
  80. Tsetting[2] = true
  81. os.sleep(0.1)
  82. else
  83. print("Контроллер не обнаружен!")
  84. Tsetting[2] = false
  85. os.sleep(0.5)
  86. end
  87. if require("component").isAvailable("crafting") then
  88. CR = require("component").crafting
  89. print('Крафтовый верстак успешно подключен')
  90. Tsetting[1] = true
  91. os.sleep(0.1)
  92. else
  93. print("Крафтовый верстак не обнаружен!")
  94. Tsetting[1] = false
  95. os.sleep(0.5)
  96. end
  97. setting[1]='Front'
  98. setting[2]='Down'
  99. setting[3]=tostring(Tsetting[2])
  100. setting[4]=tostring(Tsetting[1])
  101. setting[5]=tostring(Tsetting[1])
  102. print('Загрузка настроек из файла ...')
  103. Settings()
  104. term.clear()
  105. end
  106.  
  107. local function frame(num, leng) --рамка. просто рамка
  108. if num == 3 then
  109. gpu.set(10, 5, '┌──────────────────────────────┐')
  110. for i=1, leng+1 do
  111. gpu.set(10, i+5, '│ │')
  112. end
  113. gpu.set(10, leng+7, '└──────────────────────────────┘')
  114. return
  115. end
  116. gpu.set(1, 1, '╔════════════════════════════════════════════════╗')
  117. if num == 1 then
  118. for i=2, 15 do
  119. gpu.set(1, i, '║ ║')
  120. end
  121. gpu.set(1, 3, '╠════════════════════════════════════════════════╣')
  122. elseif num == 2 then
  123. frame(1)
  124. gpu.set(1, 8, '╠════════════════════════════════════════════════╣')
  125. end
  126. gpu.set(1, 16, '╚════════════════════════════════════════════════╝')
  127. end
  128.  
  129. function controlKey(num, smL, smR, str, rem) --контроллер клавиатуры со встроенным указателем
  130. if str == nil then str = 1 end
  131. if rem == nil then rem = 3 end
  132. gpu.set(smL, str+rem, " => ")
  133. gpu.set(50-smR-4, str+rem, " <= ")
  134. while true do
  135. local a = {event.pull('key_up')}
  136. if a[4] == 208 then --v
  137. if str == num then
  138. gpu.set(smL, str+rem, " ")
  139. gpu.set(50-smR-4, str+rem, " ")
  140. str = 1
  141. gpu.set(smL, str+rem, " => ")
  142. gpu.set(50-smR-4, str+rem, " <= ")
  143. else
  144. gpu.set(smL, str+rem, " ")
  145. gpu.set(50-smR-4, str+rem, " ")
  146. str = str + 1
  147. gpu.set(smL, str+rem, " => ")
  148. gpu.set(50-smR-4, str+rem, " <= ")
  149. end
  150. elseif a[4] == 200 then --^
  151. if str == 1 then
  152. gpu.set(smL, str+rem, " ")
  153. gpu.set(50-smR-4, str+rem, " ")
  154. str = num
  155. gpu.set(smL, str+rem, " => ")
  156. gpu.set(50-smR-4, str+rem, " <= ")
  157. else
  158. gpu.set(smL, str+rem, " ")
  159. gpu.set(50-smR-4, str+rem, " ")
  160. str = str - 1
  161. gpu.set(smL, str+rem, " => ")
  162. gpu.set(50-smR-4, str+rem, " <= ")
  163. end
  164. elseif a[4] == 28 then --
  165. return str
  166. elseif a[4] == 205 then -->
  167. return str, 1
  168. elseif a[4] == 203 then --<
  169. return str, -1
  170. end
  171. end
  172. end
  173.  
  174. local function printMenu(items, sh, x, y)--выводит на экран список меню. список, центровать или ручное смещение, смещение по Х, начать со строки
  175. if y == nil then y = 3 end
  176. local i1 = 2
  177. if sh then
  178. gpu.set(math.ceil(25-(unicode.len(items[1])/2)), 2, tostring(items[1]))
  179. else
  180. i1 = 1
  181. end
  182. for i = i1, #items do
  183. y = y+1
  184. if x == nil then
  185. gpu.set(math.ceil(25-(unicode.len(items[i])/2)), y, tostring(items[i]))
  186. else
  187. gpu.set(x, y, tostring(items[i]))
  188. end
  189. end
  190. end
  191.  
  192. local function compressionText(text, num, x, y, width, height, display) --текст, страница, начало по Х, Y, ширина, высота, отображение; подгонка текста под рамку
  193. if x == nil or y == nil then
  194. x = 2
  195. y = 3
  196. width = 47
  197. height = 12
  198. gpu.fill(x, 4, width, height, ' ')
  199. end
  200. num = (num-1)*width*height
  201. for i = 1, height do
  202. if unicode.sub(text, ((i-1)*width)+num, ((i*width)-1)+num) == '' then
  203. return true, i
  204. else
  205. if not display then
  206. gpu.set(x, i+y, unicode.sub(text, ((i-1)*width)+num, ((i*width)-1)+num))
  207. end
  208. end
  209. end
  210. if unicode.sub(text, ((height-1)*width)+num, (height*width)-1+num)~='' then
  211. return false
  212. end
  213. end
  214.  
  215. local function ScreenBuffer(x1, y1, x2, y2, save) --Буфер экрана. Вырезает кусок экрана, потом возвращает. цвета не учитывает
  216. if save then
  217. Buffer = {}
  218. for i = y1, y2 do
  219. Buffer[i] = ''
  220. for i1 = x1, x2 do
  221. local s = gpu.get(i1, i)
  222. Buffer[i] = Buffer[i]..s
  223. end
  224. end
  225. gpu.fill(x1, y1, x2-x1, (y2-y1)+1, ' ')
  226. else
  227. for i = y1, y2 do
  228. gpu.set(x1, i, Buffer[i])
  229. end
  230. Buffer = {}
  231. end
  232. end
  233.  
  234. local function confirmation(quest, agr) --вопрос, согласие(ОК) --окно запроса на подтверждение действия
  235. local uc, uc1, mem, num = -1, 0, ''
  236. _, num = compressionText(quest, 1, 12, 5, 29, 12, true)
  237. --mem = math.floor((computer.freeMemory()*100)/computer.totalMemory())..'/' -- вывод информации по памяти
  238. ScreenBuffer(10, 5, 42, 7+num, true)
  239. --mem = mem..math.floor((computer.freeMemory()*100)/computer.totalMemory())..' %' --работает невероятно криво. не запускать
  240. frame(3, num)
  241. compressionText(quest, 1, 12, 5, 29, num)
  242. if agr then
  243. gpu.set(24, num+6, '[ОК]')
  244. gpu.set(30, num+6, mem)
  245. else
  246. gpu.set(15, num+6, '[Да]')
  247. gpu.set(22, num+6, mem)
  248. gpu.set(32, num+6, '[Нет]')
  249. end
  250. os.sleep(0.1)
  251. repeat
  252. if agr then
  253. _, uc = controlKey(1, -10, -10)
  254. if uc == nil then
  255. ScreenBuffer(10, 5, 42, 7+num, false)
  256. return true
  257. end
  258. else
  259. if uc == -1 then
  260. gpu.set(28, num+6, ' ')
  261. uc1 = true
  262. _, uc = controlKey(1, 11, 50, 1, num+5)
  263. elseif uc == 1 then
  264. gpu.set(11, num+6, ' ')
  265. uc1 = false
  266. _, uc = controlKey(1, 28, 50, 1, num+5)
  267. else
  268. ScreenBuffer(10, 5, 42, 7+num, false)
  269. return uc1 --1 = да; 0 = нет
  270. end
  271. end
  272. until false
  273. end
  274.  
  275. local function menuSetting() --меню настроек
  276. local y, y1, p, Set = 1, 1, 1, {}
  277. setting[6] = ''
  278. term.clear()
  279. frame(1)
  280. local items = {"Настройка", "Сторона ловли: ", "Сторона выгрузки: ", "Автопоиск удочки: ", "Автокрафт: ", "Починка удочек: ", "[Выйти и сохранить]"}
  281. Set[1] = {[1] = 'Front', [2] = 'Up', [5] = setting[1]}
  282. Set[2] = {[1] = 'Down', [2] = 'Up', [3] = 'Front', [5]=setting[2]}
  283. if Tsetting[2] then --проверка на контроллер
  284. Set[3] = {[1]=true, [2]=false, [5]=tostring(setting[3])}
  285. else
  286. Set[3] = {[1]=false, [2]=false, [5]=false}
  287. end
  288. for i = 4, 5 do
  289. if Tsetting[1] and Tsetting[2] then --толку от автокрафта и починки нету если нету контороллера
  290. Set[i] = {[1]=true, [2]=false, [5]=tostring(setting[i])}
  291. else
  292. Set[i] = {[1]=false, [2]=false, [5]=false}
  293. end
  294. end
  295. printMenu(items, true, 4)
  296. printMenu(setting, false, 24)
  297. os.sleep(0.1)
  298. repeat
  299. y, uc = controlKey(#items-1, -5, 15, y) --строка, боковые клавиши
  300. if uc ~= nil then
  301. if y ~= y1 then y1 = y p = 1 end
  302. p = p+tonumber(uc)
  303. if p == 0 then --круговой переключатель горизонтальный
  304. if y == 2 then p = 3
  305. else p = 2 end
  306. elseif p == 3 and y ~= 2 then p = 1
  307. elseif p == 4 and y == 2 then p = 1
  308. end
  309. if y ~= 6 then --проверка на выход
  310. gpu.set(24, y1+3, ' ')
  311. gpu.set(24, y+3, tostring(Set[y][p]))
  312. Set[y][5]=Set[y][p] --переменная запись для сохранения настроек
  313. else
  314. break
  315. end
  316. end
  317. until uc == nil
  318. for i=1, 5 do
  319. setting[i] = Set[i][5]
  320. --print(setting[i])
  321. end
  322. if setting[1] == setting[2] then
  323. if confirmation('Ошибка! Стороны выгрузки и ловли не могут быть одинаковыми. Желаете исправить?') then
  324. menuSetting()
  325. else
  326. setting[1] = 'Front'
  327. setting[2] = 'Down'
  328. Settings(true) --перезапись файла с настройками
  329. end
  330. else
  331. Settings(true) --перезапись файла с настройками
  332. end
  333. end
  334.  
  335. local function menuHelp() --справка
  336. term.clear()
  337. frame(1)
  338. local items = {"Справка", "Содержание:", " 1.Конфигурация робота", " 2.Сборка робота", " 3.Сборка фермы", " 4.Настройка программы", "[Назад]"}
  339. local help, y, uc = {}
  340. help[0] = "Перемещение по меню производится при помощи стрелок [↑] [↓] на клавиатуре, подтверждение выбора - [Enter]. Для перехода на следующую страницу нажмите [→], для возврата [←]. Чтобы вернуться к содержанию, из любого места в тексте, нажмите [Enter]."
  341. help[1] = "Много текста про 1.Конфигурация робота"
  342. help[2] = "Много текста про 2.Сборка робота"
  343. help[3] = "Много текста про 3.Сборка фермы"
  344. help[4] = "Много текста про 4.Настройка программы"
  345. printMenu(items, true, 6)
  346. os.sleep(0.1)
  347. repeat
  348. y, uc = controlKey(#items-2, 2, -5, y, 4)
  349. if uc == nil and y ~= 5 then
  350. local i, ex = 1, false
  351. repeat
  352. if not ex then
  353. ex = compressionText(help[y], i)
  354. end
  355. local y1, uc = controlKey(1, -5, -5, 1)
  356. if uc == 1 and ex then gpu.set(2, 15, 'Для возврата нажмите [enter]')
  357. elseif uc == 1 then i = i+1
  358. elseif uc == -1 and i-1>0 then i = i-1
  359. elseif y1 == 1 and uc == nil then break end
  360. until false
  361. break
  362. end
  363. until y == 5 and uc == nil
  364. if y ~= 5 then menuHelp() end
  365. end
  366.  
  367. local function menuAbout() --о программе
  368. term.clear()
  369. frame(1)
  370. local items = {"О программе"}
  371. printMenu(items, true)
  372. compressionText("Программа 'Роборыболов v0.1' создана для игры Minecraft с модом OpenComputers (далее ОС). Она позволяет автоматизировать процесс ловли рыбы при помощи робота из ОС. Разработана для проекта http://computercraft.ru 2016, © Asior", 1)
  373. os.sleep(0.1)
  374. controlKey(1, -5, -5, 1)
  375. end
  376.  
  377. local function printCmd(sms, text) --статус строка
  378. if text ~= nil then
  379. sms[#sms+1] = text
  380. end
  381. while #sms>7 do
  382. table.remove(sms, 1)
  383. end
  384. gpu.fill(2, 9, 47, 7, ' ')
  385. for i = 1, 7 do
  386. if sms[i] ~= nil then
  387. gpu.set(2, 8+i, tostring(unicode.sub(sms[i], 1, 47)))
  388. end
  389. end
  390. return sms
  391. end
  392.  
  393. local function checkingInDatabase(name, cmd) --проверка на наличие предмета в черном списке
  394. for i = 1, #black_list do
  395. if name == black_list[i] then
  396. cmd[#cmd+1] = 'Error object in the database.'
  397. return cmd
  398. else
  399. if i == #black_list then
  400. black_list[#black_list+1] = name
  401. cmd[#cmd+1] = 'Import '..black_list[#black_list]
  402. end
  403. end
  404. end
  405. return cmd
  406. end
  407.  
  408. local function searchMarches(mass) --Поиск повторяющихся элементов в массиве и избавление от них
  409. print(#mass)
  410. local elem = mass[1]
  411. local i1 = 2
  412. repeat
  413. i = i1
  414. while i < #mass do
  415. if elem == mass[i] then
  416. print('del '..mass[i])
  417. table.remove(mass, i)
  418. else
  419. i = i+1
  420. end
  421. end
  422. i1 = i1+1
  423. elem = mass[i1+1]
  424. until i1 > #mass
  425. print(#mass)
  426. os.sleep(2)
  427. return mass
  428. end
  429.  
  430. local function printList(str, an)
  431. str = (str*11)-11
  432. gpu.fill(2, 4, 47, 12, ' ')
  433. gpu.set(6, 15, '[Назад]')
  434. for i = 1, 11 do
  435. if black_list[i+str] ~= nil then
  436. gpu.set(6, i+3, tostring(unicode.sub(black_list[i+str], 1, 40)))
  437. end
  438. end
  439. if an then
  440. local list = 1
  441. while black_list[((list+1)*11)-11] ~= nil do
  442. list = list+1
  443. end
  444. return list
  445. end
  446. end
  447.  
  448. local function editorDrop() --редактор черного списка
  449. local y, uc, list, str = 1, 1, 1
  450. frame(1)
  451. printMenu({"Редактор черного списка"}, true)
  452. str = '/'..printList(1, true)
  453. gpu.set(44, 2, '1'..str)
  454. os.sleep(0.1)
  455. repeat
  456. y, uc = controlKey(12, 2, -5, y)
  457. if y == 12 and uc == nil then
  458. break
  459. end
  460. if uc == 1 then
  461. if black_list[((list+1)*11)-11] ~= nil then
  462. list = list+1
  463. gpu.set(44, 2, ' '..list..str..' ')
  464. printList(list)
  465. end
  466. elseif uc == -1 then
  467. if list-1>0 then
  468. list = list-1
  469. gpu.set(44, 2, ' '..list..str..' ')
  470. printList(list)
  471. end
  472. else
  473. if black_list[(list*11)-11+y] ~= nil and confirmation('Вы действительно хотите удалить данный элемент?') then
  474. table.remove(black_list, (list*11)-11+y)
  475. printList(list)
  476. end
  477. end
  478. until false
  479. for i = 1, #black_list do
  480. if black_list[i] == 'nil' then
  481. break
  482. else
  483. if i == #black_list then
  484. black_list[#black_list+1] = 'nil'
  485. end
  486. end
  487. end
  488. end
  489.  
  490. local function menuDrop() --меню черного списка
  491. if not Tsetting[2] then
  492. confirmation('Отсутствует контроллер инвентаря. Данная опция недоступна', true)
  493. return
  494. end
  495. term.clear()
  496. frame(2)
  497. r.select(1)
  498. local items = {"Черный список дропа", "Добавить из слота: 1", "[Редактировать список]", "[Очистить список]", "[Назад]"}
  499. local help, y, uc, num = {}, 1, 1, 1
  500. local cmd = {'Выберите номер слота кнопками [←][→] положите', "туда предмет который робот должен игнорировать", "и нажмите [Enter]. Обратите внимание, предметы", " из некоторых модов могут отображаться некор-", "ректно."}
  501. printMenu(items, true, 6)
  502. os.sleep(0.1)
  503. cmd = printCmd(cmd)
  504. repeat
  505. y, uc = controlKey(#items-1, 2, 50, y)
  506. if y == 1 and uc ~= nil then --выбор слота
  507. if uc == 1 then
  508. if num+1>Tsetting[3] then
  509. num = 0
  510. gpu.set(25, 4, 'Все')
  511. else
  512. num = num+1
  513. r.select(num)
  514. gpu.set(25, 4, num..' ')
  515. end
  516. elseif uc == -1 then
  517. if num-1<1 then
  518. num = Tsetting[3]+1
  519. gpu.set(25, 4, 'Все')
  520. else
  521. num = num-1
  522. r.select(num)
  523. gpu.set(25, 4, num..' ')
  524. end
  525. end
  526. elseif y == 1 and uc == nil then --если выбрали 1 пункт
  527. if num == 0 or num == Tsetting[3]+1 then --прогон всех слотов
  528. for i = 1, Tsetting[3] do
  529. if incontrol.getStackInInternalSlot(i) ~= nil then
  530. cmd = printCmd(checkingInDatabase(incontrol.getStackInInternalSlot(i).name, cmd))
  531. end
  532. end
  533. else
  534. if incontrol.getStackInInternalSlot(num) ~= nil then
  535. cmd = printCmd(checkingInDatabase(incontrol.getStackInInternalSlot(num).name, cmd))
  536. else
  537. cmd = printCmd(cmd, 'Slot '..num..' is empty')
  538. end
  539. end
  540. elseif y == 2 and uc == nil then
  541. cmd = printCmd(cmd, 'Запуск редактора ...')
  542. editorDrop()
  543. break
  544. elseif y == 3 and uc == nil then
  545. if confirmation('Вы действительно хотите ОЧИСТИТЬ СПИСОК?') then
  546. cmd = printCmd(cmd, "Очищение "..#black_list..' элементов')
  547. black_list = {'nil'}
  548. cmd = printCmd(cmd, "Успешно очищено")
  549. end
  550. elseif y == #items-1 and uc == nil then
  551. black_list = searchMarches(black_list)
  552. Settings(true)
  553. return
  554. end
  555. until false
  556. r.select(1)
  557. menuDrop()
  558. end
  559.  
  560. local function printCounter(counter, num) --массив, ячейка; отображение данных счетчика
  561. for i = 1, #counter do
  562. if num == nil and i ~= #counter then
  563. gpu.set(21, i+3,tostring(counter[i])..' ')
  564. elseif num == i then
  565. gpu.set(21, i+3,tostring(counter[i])..' ')
  566. elseif i == #counter then
  567. gpu.set(2, 15,(" "):rep(29))
  568. gpu.set(3, 15,tostring(counter[i]))
  569. end
  570. end
  571. end
  572.  
  573.  
  574. local function sideNumber(side) --возвращает номер стороны
  575. local i = 0
  576. if side == 'Down' then i=0
  577. elseif side == 'Up' then i=1
  578. elseif side == 'Front' then i=3
  579. end
  580. return i
  581. end
  582.  
  583. local function useSide(side)
  584. side = sideNumber(side)
  585. if side == 1 then r.useUp()
  586. elseif side == 3 then r.use(0)
  587. end
  588. end
  589.  
  590. local function dropSide(side, opposite)
  591. if r.count()>0 and not opposite then
  592. if side == 0 then return r.dropDown(64)
  593. elseif side == 1 then return r.dropUp(64)
  594. elseif side == 3 then return r.drop(64)
  595. end
  596. elseif r.count()>0 and opposite then
  597. if side == 0 then dropSide(1)
  598. elseif side == 1 then dropSide(0)
  599. elseif side == 3 then dropSide(1)
  600. end
  601. else
  602. return true
  603. end
  604. end
  605.  
  606. local function findItem(side, name, dam) --ищет в сундуке удочку, или указанное имя
  607. if name == nil then name = 'minecraft:fishing_rod' end
  608. local inv, item = incontrol.getInventorySize(side)
  609. if inv then
  610. for slot = 1, inv do
  611. item = incontrol.getStackInSlot(side, slot)
  612. if item ~= nil and item.name == name then
  613. if dam == nil then
  614. if item.damage <= 55 then
  615. return slot
  616. end
  617. else
  618. return slot
  619. end
  620. end
  621. end
  622. end
  623. return nil
  624. end
  625.  
  626. local function itemDrop(sideInv) --очистка инвентаря
  627. local vr, vr1 = 0, 0 --для возврата статистики
  628. for i = 1, Tsetting[3] do
  629. r.select(i)
  630. if Tsetting[2] then --если есть контроллер то подключаем черный список
  631. for i1 = 1, #black_list do
  632. if incontrol.getStackInSlot(sideInv, i) ~= nil and incontrol.getStackInSlot(sideInv, i).name == black_list[i1] then
  633. vr1 = vr1 + r.count()
  634. dropSide(sideInv, true)
  635. end
  636. end
  637. end
  638. vr = vr + r.count()
  639. if not dropSide(sideInv) then
  640. printCounter({'Кажется нет места'})
  641. r.setLightColor(0xFF0000)
  642. computer.beep(2000,5)
  643. os.sleep(5)
  644. printCounter({'Повторная выгрузка'})
  645. itemDrop(sideInv)
  646. break
  647. end
  648. end
  649. r.select(1)
  650. return vr1, vr
  651. end
  652.  
  653. local function repairsFind(side, c1) --рекурсивный ремонтник удочек, не остановится пока все не починит
  654. local StatusList, vr = {}, 0
  655. local inv, item = incontrol.getInventorySize(side)
  656. for slot = 1, inv do
  657. item = incontrol.getStackInSlot(side, slot)
  658. if item ~= nil and item.name == 'minecraft:fishing_rod' and item.damage > 0 then
  659. StatusList[slot] = item.damage
  660. --print(slot..' = '..StatusList[slot]..'||'..#StatusList)
  661. else
  662. StatusList[slot] = ''
  663. end
  664. end
  665. i=1
  666. repeat
  667. if StatusList[i] ~= '' then
  668. for i1 = i+1, inv-1 do
  669. if StatusList[i1] ~= '' and (64-StatusList[i]+64-tonumber(StatusList[i1]))+3 <= 64 then
  670. r.select(1)
  671. incontrol.suckFromSlot(side, i)
  672. r.select(2)
  673. incontrol.suckFromSlot(side, i1)
  674. CR.craft()
  675. os.sleep(0.5)
  676. --print('нашел для ремонта'..i..'||'..i1..' = '..(64-StatusList[i]+64-StatusList[i1])+3)
  677. itemDrop(side)
  678. c1 = #StatusList + c1
  679. StatusList = {}
  680. break
  681. end
  682. end
  683. end
  684. i=i+1
  685. until #StatusList == 0 or i == inv
  686. if #StatusList == 0 then repairsFind(side, c1) else return c1 end
  687. end
  688.  
  689. local function craftFind(side) --крафт удочки
  690. local Recipe = {
  691. '', '', 'minecraft:stick', '',
  692. '', 'minecraft:stick', 'minecraft:string', '',
  693. 'minecraft:stick', '', 'minecraft:string', ''}
  694. for i = 1, #Recipe do
  695. if Recipe[i] ~= '' then
  696. local vr = nil
  697. vr = findItem(side, Recipe[i],0)
  698. if vr ~= nil then
  699. r.select(i)
  700. incontrol.suckFromSlot(side, vr, 1)
  701. else
  702. return false
  703. end
  704. end
  705. end
  706. CR.craft()
  707. return true
  708. end
  709.  
  710. local function noSignal() --определяем причину отсутствия сигнала от датчика
  711. if r.durability() == nil then
  712. printCounter({'Сперли удочку блин'})
  713. if setting[3] then
  714. r.select(Tsetting[3])
  715. slot = findItem(sideNumber(setting[2]))
  716. if slot then
  717. incontrol.suckFromSlot(sideInv, vr)
  718. incontrol.equip()
  719. else
  720. printCounter({'Удочка не найдена'})
  721. end
  722. r.select(1)
  723. else
  724. printCounter({'Удочка сломана совсем.'})
  725. confirmation('Удочка сломана совсем. Починка невозможна. Дайте новую удочку.', true)
  726. end
  727. elseif incontrol and setting[3] then
  728. r.select(Tsetting[3])
  729. incontrol.equip()
  730. if incontrol.getStackInInternalSlot(Tsetting[3]).name == 'minecraft:fishing_rod' then
  731. printCounter({'Удочка на месте'})
  732. incontrol.equip()
  733. r.select(1)
  734. printCounter({'Нет сигнала от датчика'})
  735. r.setLightColor(0xFF0000)
  736. computer.beep(2000, 5)
  737. os.exit()
  738. else
  739. printCounter({'Зачем мне сунули '..incontrol.getStackInInternalSlot(Tsetting[3]).label})
  740. end
  741. else
  742. printCounter({'Нет сигнала от датчика'})
  743. r.setLightColor(0xFF0000)
  744. computer.beep(2000, 5)
  745. os.exit()
  746. end
  747. end
  748.  
  749. local function repairsReplacementCraft(sideInv)
  750. local vr, c = nil, {0,0,0,0}
  751. printCounter({'Очищаю инвентарь'})
  752. c[3], c[4] = itemDrop(sideInv) --умная очистка
  753. r.select(Tsetting[3])
  754. if setting[3] then
  755. printCounter({'Извлекаю из руки'})
  756. os.sleep(0.1)
  757. incontrol.equip()
  758. vr = findItem(sideInv)
  759. end
  760. if setting[5] then
  761. printCounter({'Запуск ремонта'})
  762. os.sleep(0.1)
  763. c[1] = repairsFind(sideInv, c[1]) --ремонт всех удочек
  764. end
  765. --1сторона ловли, 2сундук сторона, 3крафт удочек, 4ремонт удочек, 5поиск и замена удочек
  766. r.select(1)
  767. os.sleep(0.1)
  768. if setting[3] and vr~=nil and incontrol.getStackInSlot(sideInv, vr).damage < 55 then --поиск удочки в сундуке и взятие в руку
  769. r.select(1)
  770. incontrol.suckFromSlot(sideInv, vr)
  771. incontrol.equip()
  772. else
  773. if setting[4] then --если крафт разрешен
  774. if craftFind(sideInv) then
  775. c[2] = repairsReplacementCraft(sideInv)
  776. else
  777. itemDrop(sideInv)
  778. end
  779. end
  780. end
  781. return c
  782. end
  783.  
  784. local function sideDrop(inv, side) --вычисление стороны сброса мусора
  785. local vr = inv + side
  786. if vr == 4 then vr = 0
  787. elseif vr == 3 then vr = 1
  788. else vr = 3 end
  789. return vr
  790. end
  791.  
  792. local function menuCatch() --
  793. frame(1)
  794. local stat = {'Load ...', 'Инвентарь - '..tostring(Tsetting[3]).." слотов", 'Контроллер - '..tostring(Tsetting[2]), 'Верстак - '..tostring(Tsetting[1]), 'Сторона ловли - '..tostring(setting[1]), 'Сторона сундука - '..tostring(setting[2]),'Поиск и замена удочек - '..tostring(setting[3]), 'Крафт удочек - '..tostring(setting[4]), 'Ремонт удочек - '..tostring(setting[5])}
  795. for i=1,#stat do
  796. gpu.set(2,i+3,stat[i])
  797. os.sleep(0.5)
  798. end
  799. os.sleep(4)
  800. local pic = {'══════════════ #', ' #·', '════════════ # ·', ' # ·', ' # ·', ' # ·', ' # ·', ' # ·', ' # ·', ' # ·', ' #: ·', ' ▒◜◝ ·', ' ▒ ◟◞ ¿', ' ▒', ' ▒ '}
  801. local rand = {'За miсо!', 'Тсс!', 'А червяки где?', 'Intel рулит!', 'С новым годом!', 'Нееет!', 'Я тут справлюсь', 'Ля-ля-ля', '-рыба', '--|=====>', '---E', 'rm *', 'ЖГИ АНТИГРАВ!!!', 'Бу-га-гашечки!', 'Есть хочешь?', 'Рыбы нету!', 'Я робот-рыболов', 'х(', 'Слава мне!', 'Эээ, руки убрал', 'Тащи динамит!', 'Скууучноооо', 'Ну почему я?', 'asior - roisa', 'o7', 'rosia', 'Hello, moto', 'AMD круче Intel', 'Intel 8080', 'Да ловлю я!', 'БОЛЬШЕ ФОСФОРА!'} --16
  802. pic[#pic] = pic[#pic]..rand[math.random(#rand)+1]
  803. local items = {'Роборыболов v0.1', 'Забросил:', 'Вытянул:', 'Вытяну через:', 'Шанс вылова:', 'Ошибок:', 'Отремонтровано:', 'Скрафчено:', 'Выброшено:', 'Сложено:', '=> [Назад]'}
  804. local con, counter = {}, {0,0,'0 сек','0 %', 0, 0, 0, 0, 0, 'status'}
  805. local err, c1, c2, c3, c4 = false
  806. frame(1)
  807. for i = 1, #pic do
  808. gpu.set(30, i, pic[i])
  809. end
  810. printMenu(items, true,4)
  811. pic, items, rand, stat = {}, {}, {}, {} --чистим память, её и так мало
  812. local sideInv = sideNumber(setting[2])
  813. local drop = sideDrop(sideInv, sideNumber(setting[1]))
  814. timer = 60
  815. os.sleep(0.1)
  816. printCounter(counter)
  817. repeat
  818. if not ((r.durability() ~= nil) and (r.durability() >= 0.1) and ((r.count(Tsetting[3]) == 0))) then --если удочка есть и прочность более 0,1 и последний слот пустой
  819. local c = {0,0,0,0}
  820. if (r.durability() ~= nil) and (r.durability() <= 0.1) and setting[5] and setting[3] then --если удочка почти сточилась и ремонт разрешен и замена разрешена
  821. counter[10] = 'Сточилась удочка, меняю'
  822. printCounter(counter, 7)
  823. c = repairsReplacementCraft(sideInv)
  824. elseif r.count(Tsetting[3]) ~= 0 then --если буфер забился
  825. counter[10] = 'Буфер полный, выгружаю'
  826. printCounter(counter, 7)
  827. c[3], c[4] = itemDrop(sideInv)
  828. elseif r.durability() == nil and setting[3] then --если нету удочки и разрешена замена
  829. counter[10] = 'Нету удочки'
  830. printCounter(counter, 7)
  831. c = repairsReplacementCraft(sideInv)
  832. end
  833. counter[6], counter[7], counter[8], counter[9] = tonumber(c[1])+counter[6], tonumber(c[2])+counter[7], tonumber(c[3])+counter[8], tonumber(c[4])+counter[9]
  834. c = {}
  835. end
  836. local tru = 0
  837. while redstone.getInput(2) + redstone.getInput(1) == 0 do
  838. r.setLightColor(0xFF0000)
  839. if tru >= 5 then
  840. noSignal()
  841. os.sleep(0.1)
  842. break
  843. end
  844. useSide(setting[1])
  845. err = true
  846. tru = tru + 1
  847. counter[5] = counter[5] + 1
  848. counter[1] = counter[1] + 1
  849. printCounter(counter)
  850. con = {event.pull(2)}
  851. if con[1] == 'key_up' and con[3] == 13 then
  852. return
  853. end
  854. end
  855. r.setLightColor(0x00FF00)
  856. con = {event.pull(1)}
  857. counter[3] = math.floor(timer)..' сек'
  858. if con[1] == 'key_up' and con[3] == 13 then
  859. return
  860. elseif con[1] == 'redstone_changed' and err then
  861. useSide(setting[1])
  862. counter[10] = 'Что-то поймал'
  863. err = false
  864. counter[2] = counter[2]+1
  865. timer = 60
  866. end
  867. counter[4] = math.floor((counter[2]*100)/counter[1])..' % '
  868. printCounter(counter)
  869. timer = timer - 1
  870. if timer == 0 then
  871. err = false
  872. counter[2] = counter[2]+1
  873. counter[10] = 'Время вышло, перезакидываю'
  874. useSide(setting[1])
  875. timer = 60
  876. end
  877. until false
  878. end
  879.  
  880. local function menu() --главное меню
  881. term.clear()
  882. frame(1)
  883. local y = 3
  884. local items = {"Роборыболов v0.1", "[Ловить рыбу]", "[Настройка]", "[Черный список дропа]", "[Справка]", "[О программе]", "[Выход]"}
  885. printMenu(items, true)
  886. os.sleep(0.1)
  887. y = 1
  888. repeat
  889. y, uc = controlKey(#items-1, 10, 10, y)
  890. if uc == nil then
  891. if y == 1 then menuCatch(); os.sleep(2) printCounter('Load ...') os.sleep(2) break;
  892. elseif y == 2 then menuSetting(); break;
  893. elseif y == 3 then menuDrop(); break;
  894. elseif y == 4 then menuHelp(); break;
  895. elseif y == 5 then menuAbout(); break;
  896. elseif y == 6 then term.clear() os.exit()
  897. end
  898. end
  899. until false
  900. menu()
  901. end
  902.  
  903. -----------------ОСНОВНОЙ КОД-----------------
  904. Tsetting = {}--крафтовый стол, контроллер инвентаря, буфер
  905. setting = {}--1сторона ловли, 2сундук сторона, 3поиск и замена удочек, 4крафт удочек, 5ремонт удочек
  906. black_list = {}
  907. Buffer = {}
  908. term.clear()
  909. componentTesting()
  910. menu()
Advertisement
Add Comment
Please, Sign In to add comment