CultistaDeCrocs

atari.lua

Mar 19th, 2024 (edited)
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.09 KB | None | 0 0
  1. -- ===== API do A.T.A.R.I. (Autômato para Tarefas Altamente Repetitivas e Inconvenientes) ===== --
  2. -- Autor: CultistaDeCrocs
  3.  
  4.  
  5. -- Variáveis
  6.  
  7. blocosLixo = {
  8. "minecraft:cobblestone",
  9. "minecraft:stone",
  10. "minecraft:dirt",
  11. "minecraft:gravel",
  12. "minecraft:tuff",
  13. "minecraft:sand",
  14. "minecraft:cobbled_deepslate",
  15. "minecraft:diorite",
  16. "minecraft:granite",
  17. "minecraft:andesite",
  18. "quark:cobbled_deepslate",
  19. }
  20.  
  21.  
  22. -- Funções de lógica
  23.  
  24. function existeEm(str, lst) -- Procura um item numa lista
  25. for i=1, #lst do
  26. if(str == lst[i]) then
  27. return true
  28. end
  29. end
  30.  
  31. return false
  32. end
  33.  
  34.  
  35. -- Funções de impressão
  36.  
  37. function writeSync(str) -- Função de write síncrona (ocorre em todos os PCS conectados)
  38. write(str)
  39. rednet.broadcast({"write", {str}}, protocolo)
  40. end
  41.  
  42. function printSync(str) -- Função de print síncrona (ocorre em todos os PCS conectados)
  43. print(str)
  44. rednet.broadcast({"print", {str}}, protocolo)
  45. end
  46.  
  47. function centralizaCursorAsync(tamanho) -- [ASSÍNCRONO] Centraliza o cursor na tela dependendo do tamanho de uma string
  48. local x, y = term.getCursorPos()
  49. local width, height = term.getSize()
  50. term.setCursorPos(math.floor((width - tamanho) / 2) + 1, y)
  51. end
  52.  
  53. function centralizaCursor(tamanho) -- Centraliza o cursor na tela dependendo do tamanho de uma string
  54. centralizaCursorAsync(tamanho)
  55.  
  56. rednet.broadcast({"centralizaCursor", {tamanho}}, protocolo)
  57. end
  58.  
  59. function printCorAsync(str, cor) -- [ASSÍNCRONO] Imprime o texto com a cor desejada, depois volta pra branco
  60. term.setTextColor(cor)
  61. print(str)
  62. term.setTextColor(colors.white)
  63. end
  64.  
  65. function printCor(str, cor) -- Imprime o texto com a cor desejada, depois volta pra branco
  66. printCorAsync(str, cor)
  67.  
  68. rednet.broadcast({"printCor", {str, cor}}, protocolo)
  69. end
  70.  
  71. function printCentro(str) -- Escreve centralizado
  72. centralizaCursor(#str)
  73. printSync(str)
  74. end
  75.  
  76. function printCentroCor(str, cor) -- Escreve centralizado e colorizado
  77. centralizaCursor(#str)
  78. printCor(str, cor)
  79. end
  80.  
  81. function writeCorAsync(str, cor) -- [ASSÍNCRONO] Imprime o texto com a cor desejada, sem \n
  82. term.setTextColor(cor)
  83. write(str)
  84. term.setTextColor(colors.white)
  85. end
  86.  
  87. function writeCor(str, cor) -- Imprime o texto com a cor desejada, sem \n
  88. writeCorAsync(str, cor)
  89.  
  90. rednet.broadcast({"writeCor", {str, cor}}, protocolo)
  91. end
  92.  
  93. function writeCentro(str) -- Escreve centralizado, sem \n
  94. centralizaCursor(#str)
  95. writeSync(str)
  96. end
  97.  
  98. function writeCentroCor(str, cor) -- Escreve centralizado e colorizado, sem \n
  99. centralizaCursor(#str)
  100. writeCor(str, cor)
  101. end
  102.  
  103. function limpaTelaAsync() -- [ASSÍNCRONO] Limpa e reseta a tela
  104. term.clear()
  105. term.setCursorPos(1,1)
  106. end
  107.  
  108. function limpaTela() -- Limpa e reseta a tela
  109. limpaTelaAsync()
  110.  
  111. rednet.broadcast({"limpaTela", {}}, protocolo)
  112. end
  113.  
  114. function printBool(str, valor) -- Imprime um valor booleano em cinza se falso e verde se verdadeiro
  115. writeSync(str..": ")
  116.  
  117. if (valor) then
  118. printCor("true", colors.lime)
  119. else
  120. printCor("false", colors.lightGray)
  121. end
  122. end
  123.  
  124. function imprimirTabela(tabela) -- Imprime uma tabela com os números coloridos
  125. for i=1, #tabela do
  126. writeCor(i, colors.orange)
  127. printSync(" "..tabela[i])
  128. end
  129. end
  130.  
  131. function imprimeDivisoriaAsync(cor) -- [ASSÍNCRONO] Imprime uma divisória que ocupa toda a tela
  132. local width, height = term.getSize()
  133. for i=1, width do
  134. writeCorAsync("=", cor)
  135. end
  136. write("\n")
  137. end
  138.  
  139. function imprimeDivisoria(cor) -- Imprime uma divisória que ocupa toda a tela
  140. imprimeDivisoriaAsync(cor)
  141.  
  142. rednet.broadcast({"imprimeDivisoria", {cor}}, protocolo)
  143. end
  144.  
  145.  
  146. -- Funções de interface de usuário
  147.  
  148. function atualizarMonitor(imprimirInformacao) -- Atualiza o monitor e executa a função de imprimir informação do programa
  149. limpaTela()
  150.  
  151. imprimeDivisoria(colors.yellow)
  152. printCentroCor("I N F O R M A C O E S", colors.orange)
  153. imprimirInformacao()
  154. imprimeDivisoria(colors.yellow)
  155. end
  156.  
  157. function imprimirCombustivel()
  158. if(turtle.getFuelLevel() == "unlimited") then
  159. writeSync("Combustível: ")
  160. printCor("ilimitado", colors.blue)
  161. elseif (turtle.getFuelLevel() > 0) then
  162. writeSync("Combustível: ")
  163. printCor(turtle.getFuelLevel(), colors.green)
  164. else
  165. writeSync("Combustível: ")
  166. printCor("0", colors.red)
  167. esperarCarvao()
  168. end
  169. end
  170.  
  171. function esperarCarvao() -- Espera chegar carvão e imprime uma mensagem
  172. printCentroCor("ALERTA: SEM COMBUSTIVEL", colors.red)
  173. printCentroCor("Por favor coloque carvão no meu slot 1.", colors.orange)
  174.  
  175. while not recarregar() do
  176. os.sleep(1)
  177. end
  178. end
  179.  
  180. function agradece(passos) -- Agradece por usar o programa
  181. limpaTela()
  182.  
  183. printCor("Obrigado por usar esse programa!\n", colors.orange)
  184. writeCor("Blocos andados: ", colors.cyan)
  185. printSync(passos)
  186. writeCor("Combustível restante: ", colors.cyan)
  187. printSync(turtle.getFuelLevel())
  188. printCor("\nfeito por CultistaDeCrocs", colors.lime)
  189. imprimeDivisoria(colors.yellow)
  190. end
  191.  
  192. function informacaoTitulo(nome) -- Imprime o título e a informação sobre o combustível
  193. limpaTela()
  194. printCentroCor("==== "..nome.." ====\n", colors.lime)
  195. end
  196.  
  197. function informacaoCombustivelNecessario(tamanho) -- Imprime informação sobre combustível se não houver o suficiente
  198. local combustivel = turtle.getFuelLevel()
  199.  
  200. if(combustivel ~= "unlimited" and combustivel < tamanho) then
  201. local combustivelNecessario = (tamanho) - combustivel
  202.  
  203. write("Eu vou precisar de ")
  204. writeCor(combustivelNecessario, colors.orange)
  205. write(" unidades de combustível. Isso é o equivalente a ")
  206. writeCor(math.ceil(combustivelNecessario/80), colors.orange)
  207. write(" unidades de carvão. Por favor coloque essa quantidade de combustível no meu primeiro slot e ")
  208. writeCor("aperte qualquer botão.\n", colors.lightBlue)
  209. write("> ")
  210. read()
  211. end
  212. end
  213.  
  214. function lerNumero() -- Lê o input e converte pra número
  215. write("\n> ")
  216. return tonumber(read())
  217. end
  218.  
  219. function pedeEscolha(maximo) -- Pede para o usuário escolher e fecha se não for válida
  220. local escolha = lerNumero()
  221.  
  222. if(escolha < 1 or escolha > maximo) then
  223. limpaTela()
  224. printCor("ERRO: Escolha inválida. Rode o programa novamente e escolha um valor válido (entre 1 e "..maximo..").", colors.red)
  225. error()
  226. else
  227. return escolha
  228. end
  229. end
  230.  
  231. -- Funções de controle do robô
  232.  
  233. function recarregar() -- Recarrega o robô
  234. turtle.select(1)
  235. return turtle.refuel()
  236. end
  237.  
  238. function jogaLixoFora() -- Dropa todos os itens do inventário que estão em blocosLixo[]
  239. for i=1, 16 do
  240. turtle.select(i)
  241. local currentItem = turtle.getItemDetail(i)
  242.  
  243. if currentItem ~= nil then
  244. if existeEm(currentItem.name, blocosLixo) then
  245. turtle.drop()
  246. end
  247. end
  248. end
  249.  
  250. counterDropar = 0
  251. turtle.select(1)
  252. end
  253.  
  254. function checaInventarioVazio() -- Retorna se o inventário está vazio
  255. for i=2, 16, 1 do
  256. turtle.select(i)
  257. if(turtle.getItemCount (i) > 0) then
  258. return false
  259. end
  260. end
  261.  
  262. return true
  263. end
  264.  
  265. function colocarBloco() -- Procura blocos no inventário e coloca
  266. local maoCheia = false
  267. local mao = 1
  268.  
  269. if checaInventarioVazio() then
  270. limpaTela()
  271. printCor("ERRO: Acabaram meus blocos. Terminando programa...", colors.red)
  272. error()
  273. end
  274.  
  275. turtle.place()
  276. end
  277.  
  278. function colocarBaixo() -- Procura blocos no inventário e coloca pra baixo
  279. local maoCheia = false
  280. local mao = 1
  281.  
  282. if checaInventarioVazio() then
  283. limpaTela()
  284. printCor("ERRO: Acabaram meus blocos. Terminando programa...", colors.red)
  285. error()
  286. end
  287.  
  288. turtle.placeDown()
  289. end
  290.  
  291.  
  292. -- Funções síncronas e suas contrapartes assíncronas
  293.  
  294. funcoesRecebe = {
  295. ["print"] = print,
  296. ["printCor"] = printCorAsync,
  297. ["write"] = write,
  298. ["writeCor"] = writeCorAsync,
  299. ["limpaTela"] = limpaTelaAsync,
  300. ["imprimeDivisoria"] = imprimeDivisoriaAsync,
  301. ["centralizaCursor"] = centralizaCursorAsync,
  302. }
  303.  
  304.  
  305. -- Funções de rednet
  306.  
  307. function procuraModem()
  308. if (peripheral.find("modem") == nil) then
  309. return false
  310. else
  311. return true
  312. end
  313. end
  314.  
  315. function estaAberto() -- Retorna se o pc está aberto à rednet
  316. for i, lado in ipairs(rs.getSides()) do
  317. if rednet.isOpen(lado) then
  318. return true
  319. end
  320. end
  321.  
  322. return false
  323. end
  324.  
  325. function recebe() -- Recebe uma mensagem e executa a função dela se existir, retornando se a função foi executada ou não
  326. local id, mensagem = rednet.receive(protocolo)
  327. local executada
  328.  
  329. -- Se a função de mensagem[1] existe em funcoesRecebe, executa ela, com os argumentos de mensagem[2]. Senão, executada = false
  330. if(funcoesRecebe[mensagem[1]]) then
  331. funcoesRecebe[mensagem[1]](unpack(mensagem[2]))
  332. executada = true
  333. else
  334. executada = false
  335. end
  336.  
  337. return mensagem, executada, id
  338. end
  339.  
  340.  
  341. -- Return da biblioteca
  342.  
  343. if (procuraModem()) then
  344. -- Retorna funções com funcionalidade síncrona, se tiver modem
  345. return {
  346. printCor = printCor,
  347. writeCor = writeCor,
  348. printCorAsync = printCorAsync,
  349. writeCorAsync = writeCorAsync,
  350. centralizaCursor = centralizaCursor,
  351. centralizaCursorAsync = centralizaCursorAsync,
  352. printBool = printBool,
  353. atualizarMonitor = atualizarMonitor,
  354. imprimirCombustivel = imprimirCombustivel,
  355. esperarCarvao = esperarCarvao,
  356. recarregar = recarregar,
  357. informacaoTitulo = informacaoTitulo,
  358. informacaoCombustivelNecessario = informacaoCombustivelNecessario,
  359. agradece = agradece,
  360. jogaLixoFora = jogaLixoFora,
  361. imprimirTabela = imprimirTabela,
  362. colocarBaixo = colocarBaixo,
  363. lerNumero = lerNumero,
  364. colocarBloco = colocarBloco,
  365. printCentro = printCentro,
  366. printCentroCor = printCentroCor,
  367. writeCentro = writeCentro,
  368. writeCentroCor = writeCentroCor,
  369. printSync = printSync,
  370. writeSync = writeSync,
  371. recebe = recebe,
  372. estaAberto = estaAberto,
  373. limpaTela = limpaTela,
  374. limpaTelaAsync = limpaTelaAsync,
  375. imprimeDivisoria = imprimeDivisoria,
  376. imprimeDivisoriaAsync = imprimeDivisoriaAsync,
  377. checaInventarioVazio = checaInventarioVazio,
  378. }
  379. else
  380. -- Senão, re-roteia as funções síncronas pra funções assíncronas
  381. return {
  382. printCor = printCorAsync,
  383. writeCor = writeCorAsync,
  384. printCorAsync = printCorAsync,
  385. writeCorAsync = writeCorAsync,
  386. centralizaCursor = centralizaCursorAsync,
  387. centralizaCursorAsync = centralizaCursorAsync,
  388. printBool = printBool,
  389. atualizarMonitor = atualizarMonitor,
  390. imprimirCombustivel = imprimirCombustivel,
  391. esperarCarvao = esperarCarvao,
  392. recarregar = recarregar,
  393. informacaoTitulo = informacaoTitulo,
  394. informacaoCombustivelNecessario = informacaoCombustivelNecessario,
  395. agradece = agradece,
  396. jogaLixoFora = jogaLixoFora,
  397. imprimirTabela = imprimirTabela,
  398. colocarBaixo = colocarBaixo,
  399. lerNumero = lerNumero,
  400. colocarBloco = colocarBloco,
  401. printCentro = printCentro,
  402. printCentroCor = printCentroCor,
  403. writeCentro = writeCentro,
  404. writeCentroCor = writeCentroCor,
  405. printSync = print,
  406. writeSync = write,
  407. recebe = recebe,
  408. estaAberto = estaAberto,
  409. limpaTela = limpaTelaAsync,
  410. limpaTelaAsync = limpaTelaAsync,
  411. imprimeDivisoria = imprimeDivisoriaAsync,
  412. imprimeDivisoriaAsync = imprimeDivisoriaAsync,
  413. checaInventarioVazio = checaInventarioVazio,
  414. }
  415. end
Advertisement
Add Comment
Please, Sign In to add comment