CultistaDeCrocs

asshat

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