Skip to content

Instantly share code, notes, and snippets.

@aferral
Last active April 28, 2019 03:33
Show Gist options
  • Save aferral/554c1234e21309f985e45ab1f6cd7047 to your computer and use it in GitHub Desktop.
Save aferral/554c1234e21309f985e45ab1f6cd7047 to your computer and use it in GitHub Desktop.
-- pastebin get 39pZ9DBg gistget
-- gistget get https://gist.github.com/aferral/554c1234e21309f985e45ab1f6cd7047
-- floppy debe estar a la izquierda
fuelSlot = 4
-- Revisa cantidad de cofres, turtle, levers, combustible
leverSlot = 1
turtleSlot = 2
chestSlot = 3
stoneSlot = 5
-- Utilidad para printear con formato estilo C
printf = function(s,...)
return io.write(s:format(...))
end -- function
-- Escribe startup script
config1 = [===[
[[
in;minecraft:gold_ore-0
in;minecraft:iron_ore-0
in;ic2:resource-3
in;ic2:resource-4
in;ic2:resource-2
in;ic2:resource-1
out;ic2:crushed-0
out;ic2:crushed-1
out;ic2:crushed-2
out;ic2:crushed-3
out;ic2:crushed-5
out;ic2:crushed-6
]]
]===]
config2 = [===[
[[
in;ic2:crushed-0
in;ic2:crushed-1
in;ic2:crushed-2
in;ic2:crushed-3
in;ic2:crushed-5
in;ic2:crushed-6
in;ic2:fluid_cell-0;6
out;ic2:dust-15
out;ic2:dust-21
out;ic2:dust-19
out;ic2:dust-26
out;ic2:dust-23
out;ic2:dust-20
out;ic2:dust-24
out;ic2:dust-27
out;ic2:dust-28
out;ic2:dust-22
out;ic2:dust-18
out;ic2:purified-0
out;ic2:purified-1
out;ic2:purified-2
out;ic2:purified-3
out;ic2:purified-4
out;ic2:purified-5
out;ic2:purified-6
]]
]===]
config3 = [===[
[[
in;ic2:purified-0
in;ic2:purified-1
in;ic2:purified-2
in;ic2:purified-3
in;ic2:purified-4
in;ic2:purified-5
]]
]===]
configs = {config1,config2,config3}
proto = [[
chestSlot = 2
leaverSlot = 3
stoneSlot = 4
shell.run('refuel')
shell.run('pastebin get 39pZ9DBg gistget')
shell.run('gistget get 554c1234e21309f985e45ab1f6cd7047')
-- Ir a ubicacion
%s
turtle.select(stoneSlot)
turtle.placeDown()
turtle.forward()
-- Colocar cofres
turtle.select(chestSlot)
turtle.placeUp()
turtle.placeDown()
turtle.turnLeft()
turtle.place()
turtle.turnRight()
%s
-- Colocar leaver
turtle.select(leaverSlot)
turtle.turnRight()
turtle.turnRight()
turtle.place()
turtle.turnRight()
turtle.turnRight()
-- Escribe configuracion
temp=fs.open('configInOut.conf', 'w')
temp.write(%s)
temp.close()
-- Inicia programa
shell.run('loadUnload configInOut.conf')
]]
for i=1,3,1 do
if (i==1) then
goto = "shell.run('go up 1'); shell.run('go forward 4'); "
elseif (i==2) then
goto = "shell.run('go up 1'); shell.run('go right 1'); shell.run('go forward 2'); shell.run('go left 1'); shell.run('go forward 4');"
elseif (i==3) then
goto = "shell.run('go up 1'); shell.run('go right 1'); shell.run('go forward 4'); shell.run('go left 1'); shell.run('go forward 4');" end
if (i==3) then
extraChest = "turtle.turnRight(); turtle.place(); turtle.turnLeft(); "
else
extraChest = ""
end
config = configs[i]
-- Escribre archivo startup
p_disk = disk.getMountPath("left")
print(p_disk)
rm_str = 'rm %s/startup'
w_str = "%s/startup"
shell.run(rm_str:format(p_disk))
file = fs.open(w_str:format(p_disk), "w")
file.write(proto:format(goto,extraChest,config))
file.close()
-- Place turtle
turtle.forward()
turtle.turnLeft()
turtle.select(turtleSlot)
turtle.place()
-- darle combustible y otras cosas que necesite
turtle.select(fuelSlot)
turtle.drop(1)
if (i==3) then
turtle.select(chestSlot)
turtle.drop(4)
else
turtle.select(chestSlot)
turtle.drop(3)
end
turtle.select(leverSlot)
turtle.drop(1)
turtle.select(stoneSlot)
turtle.drop(1)
-- Iniciar turtle creada
peripheral.call("front", 'turnOn')
turtle.turnRight()
turtle.back()
os.sleep(4)
end
local component = require("component")
local computer = require("computer")
local i_comp = component.proxy(component.list("internet")())
local out_folder_name = "gist_folder"
local function get_request_handler(url)
--local elem_d = component.proxy(component.list("internet")())
local code = 200
local message = ""
local r_h = nil
local data=""
local chunck = ""
local handle, reason = i_comp.request(url)
-- Check if the requests is ready to be read
local startTime = computer.uptime()
local TIMEOUT = 2
local result,ready = false,false
while true do
result, ready = pcall(handle.finishConnect)
if result and ready then
break
elseif not result then
print("Could not connect to " .. url .. ".")
os.exit()
elseif computer.uptime() - startTime > TIMEOUT then
print("Request to " .. url .. " timed out")
os.exit()
else
os.sleep(0.25)
end
end
if ready then
code,message,r_h = handle.response()
print(code,message)
if code ~= 200 then
local error_msg = "Error. Request code : " .. tostring(code)
if message then
error_msg = error_msg .. message
end
error(error_msg)
end
return handle
else
print(reason .. "\n")
error("Error in handle")
end
return data
end
assert(i_comp.isHttpEnabled())
--[[
Tests
local data_res = ""
data_res = get_request("https://raw.githubusercontent.com/IgorTimofeev/MineOS/master/Installer/Main.lua")
data_res = get_request("https://ap554c1234e2as.com")
]]
-- Install JSON parser in /usr/lib/ or a valid path
json_file_url = "https://raw.githubusercontent.com/jiyinyiyong/json-lua/master/JSON.lua"
local handle = get_request_handler(json_file_url)
local temp_buffer = nil
local f = require("filesystem")
if f.get("/lib").isReadOnly() then
temp_buffer=io.open("JSON.lua",'w')
else
temp_buffer = io.open("/lib/JSON.lua",'w')
end
-- Read response content
while true do
chunk, reason = handle.read(math.huge)
if chunk then
temp_buffer:write(chunk)
else
if reason then
error("JSON libs request : " .. tostring(reason))
end
break
end
end
handle.close()
temp_buffer:close()
--
-- parse JSON
local json = require("JSON")
local shell = require("shell")
local gist_url = "https://api.github.com/users/aferral/gists"
gist_url = "https://api.github.com/gists/554c1234e21309f985e45ab1f6cd7047"
local handle_gist = get_request_handler(gist_url)
local raw_json_text = ""
-- Read response content
while true do
chunk, reason = handle_gist.read(1000)
if chunk then
raw_json_text = raw_json_text .. chunk
-- temp_f:write(chunk)
else
if reason then
error("JSON libs request : " .. tostring(reason))
end
break
end
end
handle_gist.close()
local gist_table, reason = json:decode(raw_json_text) -- decode example
if reason then
error(reason)
end
-- create folder for files
local out_folder_full_path = f.concat(shell.getWorkingDirectory() , out_folder_name)
if not f.exists(out_folder_full_path) then
assert(f.makeDirectory(out_folder_full_path))
end
-- Iterate files
for k,v in pairs(gist_table.files) do
-- get filename and content
local filename = v.filename
local out_path = f.concat(out_folder_full_path, filename)
assert(not f.get(out_path).isReadOnly())
print(filename)
-- write content in folder
local fd = io.open(out_path,'w')
fd:write(v.content)
fd:close()
end
--[[
Vista desde arriba de sistema
I T O
A la izquierda el cofre de elementos de entrada.
En el medio el turtle.
A la derecha el cofre de salida.
Arriba del turtle debe estar el cofre de elementos sobrantes
Abajo debe estar combustible.
Normalmente solo maneja colocar/sacar items de a grupo. Tiene una funcion para
repartir items equitativamente ya que por defecto dejaria todos en una sola accion.
]]--
function tableSize(T)
lengthNum= 0
for k, v in pairs(T) do -- for every key in the table with a corresponding non-nil value
lengthNum = lengthNum + 1
end
return lengthNum
end
-- Consigue todo lo que puedas del cofre en frente
function getAllInChest()
while (turtle.suck()) do
end
end
-- Filtra elementos que no estan el lista de input. Lo que sobra al cofre de arriba
function storeUnrecognizedInputItems(allowedInputs,toDistribute)
remainingInputs = {}
fillElementDict = {}
toFill=1
for i=1,16,1 do
turtle.select(i)
det = turtle.getItemDetail()
if (det) then
stringId = (det.name .. "-" .. det.damage)
print("En inventario " .. stringId)
if(toDistribute[stringId]) then
print("Tipo input refill")
-- acomoda al inicio
turtle.transferTo(toFill)
-- Guarda lista de indices con elementos
if (fillElementDict[stringId]) then
table.insert(fillElementDict[stringId],toFill)
else
fillElementDict[stringId] = {}
table.insert(fillElementDict[stringId],toFill)
end
toFill = toFill +1
elseif (allowedInputs[stringId]) then
print("Presente en INPUTS validos")
-- acomoda al inicio
turtle.transferTo(toFill)
table.insert(remainingInputs, toFill)
toFill = toFill +1
else
print("No esta en INPUTS validos se filtra")
turtle.dropUp()
end
end
end
return remainingInputs,fillElementDict
end
-- Elementos out a derecha, elementos input a izq elementos extras arriba
-- TODO a donde deberia quedarse el refill?
function storeOutputs(allowedInputs,allowedOutputs,toDistribute)
-- Revisa por inputs no usados
turtleMov.tLeft()
for i=1,16,1 do
turtle.select(i)
det = turtle.getItemDetail()
if (det) then
stringId = (det.name .. "-" .. det.damage)
if (allowedInputs[stringId] ) then
turtle.drop()
end
end
end
turtleMov.tRight()
-- Revisa por outputs
turtleMov.tRight()
for i=1,16,1 do
turtle.select(i)
det = turtle.getItemDetail()
if (det) then
stringId = (det.name .. "-" .. det.damage)
if (allowedOutputs[stringId]) then
turtle.drop()
end
end
end
turtleMov.tLeft()
-- Lo demas arriba
for i=1,16,1 do
turtle.select(i)
det = turtle.getItemDetail()
if (det) then
turtle.dropUp()
end
end
end
os.loadAPI("turtleMov")
args = {...}
allowedInputs = {}
allowedOutputs = {}
toDistribute = {}
configFile = args[1]
file=fs.open(configFile,'r')
stringAll = file.readAll()
file.close()
-- Entradas de formado (in/out);itemName;damage
-- Se usa damage debido a que ciertos mods identifican items con el par itemString,name (ejemplo polvos del ic2)
-- Configura lista de elementos a cargar en maquinas
-- Configura lista de elemtnso a descargar en output
for configEntry in stringAll:gmatch("%S+") do
sepPlace = string.find(configEntry,";")
inOrOut = string.sub(configEntry,0,sepPlace-1)
id_string = string.sub(configEntry,sepPlace+1,-1)
if (inOrOut == "in") then
-- Caso especial para repartor items
extra = string.find(id_string,";")
if (extra) then
realId = string.sub(id_string,0,extra-1)
extraV = string.sub(id_string,extra+1,-1)
print("INPUT se repartiran " .. extraV .. " de " .. realId .. " a cada maquina")
toDistribute[realId] = tonumber(extraV)
else
turtleMov.printf("INPUT identificador %s \n",id_string)
allowedInputs[id_string] = 1
end
elseif (inOrOut == "out") then
turtleMov.printf("OUTPUT identificador %s \n",id_string)
allowedOutputs[id_string] = 1
else
error("Argumento mal formateado deberia ser (in/out);itemName-damage es ".. configEntry)
end
end
-- Sleep hasta evento de redstone
while true do
print( "Esperando partida (redstone signal) " )
local event, key = os.pullEvent( "redstone" )
print("Redstone signal recivida")
-- Realiza checkeo de combustible
turtleMov.checkFuel(20) -- Revisa que al menos tenga 20 (intenta refuel de lo contrario)
-- Saca todos los elementos a izquierda
turtleMov.tLeft()
getAllInChest()
turtleMov.tRight()
-- Filtra segun elementos colocables (deja arriba extras)
remainingInputs,fillElementDict = storeUnrecognizedInputItems(allowedInputs,toDistribute)
-- Primer paso para salir de cofres
turtleMov.forw()
-- Avanza hasta no detectar maquinas arriba
while (turtle.detectUp()) do
success,metadata = turtle.inspectUp()
print(metadata.state.type)
-- Intenta refill equitativo de haberlo
for idStringRefill,listOfSlots in pairs(fillElementDict) do
ammout = toDistribute[idStringRefill]
print("Inicia refill de "..idStringRefill .. " n: " .. ammout)
slot = table.remove(listOfSlots)
if (slot) then
turtle.select(slot)
assert(turtle.dropUp(ammout))
if (turtle.getItemCount() > 0) then
table.insert(listOfSlots,slot)
end
else
print("SIN refill de "..idStringRefill )
end
end
-- TODO posible mejora de chequear refills sistema de reparto ??
if (string.find(metadata.state.type,"active")) then
print("Maquina observada ACTIVA")
else -- Colocar elementos si la maquina este desocupada
print("Maquina observada INACTIVA")
if (tableSize(remainingInputs) > 0) then
element = table.remove(remainingInputs)
turtle.select(element)
assert(turtle.dropUp())
end
end
-- Sacar elementos de maquina
while(turtle.suckUp()) do
end
turtleMov.forw()
end
-- Volver a inicio
turtleMov.retorno()
-- Dejar lo que se deba en cofre de salida
-- Los inputs son usar devuelta a cofre de entrad
-- Lo demas en cofre extra
storeOutputs(allowedInputs,allowedOutputs,toDistribute)
end
-- Utilidad para printear con formato estilo C
printf = function(s,...)
return io.write(s:format(...))
end -- function
-- Sea un floppy, un disco y turtles, combustible, celdas de lava
floppySlot = 1
driveSlot = 2
fuelSlot = 3
turtleSlot = 4
tntSlow = 5
-- Al iniciar se pide un cuadrante relativo a posicion
alturaMin = 0
alturaMax = 0
norteMin = 0
norteMax = 0
esteMin = 0
esteMax = 0
local tArgs = { ... }
if #tArgs < 6 then
print "Faltan argumentos altMin, alturaMax , norteMin, norteMax , esteMin, esteMax"
return
end
printf("alturas (%d %d), norte (%d %d) , este (%d %d) \n",alturaMin,alturaMax,norteMin,norteMax,esteMin,esteMax)
alturaMin= tonumber(tArgs[1])
alturaMax=tonumber(tArgs[2])
norteMin=tonumber(tArgs[3])
norteMax=tonumber(tArgs[4])
esteMin=tonumber(tArgs[5])
esteMax=tonumber(tArgs[6])
-- Toma un fuel
turtle.select(fuelSlot)
turtle.refuel(1)
-- Coloca lector y floppy
turtle.select(driveSlot)
turtle.forward()
turtle.turnLeft()
turtle.place()
turtle.select(floppySlot)
turtle.place()
-- Vuelve posicion inicial
turtle.turnRight()
turtle.back()
-- TODO DEPLOY ESCRIBIR PROGRAMA
-- TODO TA MAL COLOCADO DISCO
-- TODO LOOP
-- Se espera senal de redstone
-- Sleep hasta evento de redstone
while true do
print( "Esperando partida (redstone signal) " )
local event, key = os.pullEvent( "redstone" )
print("Redstone signal recivida")
-- Genera posicion aleatoria en cuadrante
alturaT = math.random (alturaMin, alturaMax)
norteT = math.random (norteMin, norteMax)
esteT = math.random (esteMin, esteMax)
printf("Enviando a ALT-NORT-ESTE (%d %d %d) \n",alturaT,norteT,esteT)
-- Place turtle
turtle.select(turtleSlot)
turtle.place()
-- Suminista 1 combustible 1 carga
turtle.select(fuelSlot)
turtle.drop(1)
turtle.select(tntSlow)
turtle.drop(1)
-- Escribe programa de mision turtle
-- Envia a objetivo
end
# Escribe programa mision turtle
#(select(1); refuel(); select(carga) go up 10; go left 10; place )
# Envia a objetivo
# Enviar hasta agotar turtles.
# Programa bombardero
# Setear avance relativo en comand line
# Cargar con reactor, X rods
# espera senal redstone
# ir a posicion seteada
# Place reactor
# Drop all rods
# Send redstone signal.
--- Apis para movimiento de turtles
-- VARIABLE GLOBALES
global_debug = 0
global_deltah=0
global_deltaw=0
global_deltad=0
global_orientacion = 0 -- Guarda global_orientacion respecto a origen. 0: frente, 1: derecha, 2: atras, 3: izquierda
-- Utilidad para printear con formato estilo C
printf = function(s,...)
return io.write(s:format(...))
end -- function
-- FUNCIONES COMBUSTIBLE
function checkFuel(cantidad)
if (turtle.getFuelLevel() < cantidad) then
printf("No hay suficiente combustible intentado refuel.")
turtle.suckDown()
local selectedSlot = turtle.getSelectedSlot()
for i=1,16,1 do
if (turtle.getItemCount(i) > 0) then
turtle.select(i)
turtle.refuel()
end
end
turtle.select(selectedSlot)
if (turtle.getFuelLevel() < cantidad) then
error("No fue posible realizar refuel y se pide mas del actual. ")
end
end
end
-- FUNCIONES NAVEGACION
function tLeft()
turtle.turnLeft()
global_orientacion = (global_orientacion-1) % 4
end
function tRight()
turtle.turnRight()
global_orientacion = (global_orientacion+1) % 4
end
function back()
if global_debug == 1 then print("b") end
if (not turtle.back()) then
error("NO se logro romper bloque")
end
if (global_orientacion == 0) then
global_deltad=global_deltad-1
end
if (global_orientacion == 1) then
global_deltaw=global_deltaw-1
end
if (global_orientacion == 2) then
global_deltad=global_deltad+1
end
if (global_orientacion == 3) then
global_deltaw=global_deltaw+1
end
end
function forw()
if global_debug == 1 then print("f") end
turtle.dig()
if (not turtle.forward()) then
os.sleep(0.2)
turtle.dig()
if (not turtle.forward()) then
error("NO se logro romper bloque")
end
end
if (global_orientacion == 0) then
global_deltad=global_deltad+1
end
if (global_orientacion == 1) then
global_deltaw=global_deltaw+1
end
if (global_orientacion == 2) then
global_deltad=global_deltad-1
end
if (global_orientacion == 3) then
global_deltaw=global_deltaw-1
end
end
function up()
if global_debug == 1 then print("up") end
turtle.digUp()
if (not turtle.up()) then
error("NO se logro romper bloque")
end
global_deltah=global_deltah+1
end
function down()
if global_debug == 1 then print("down") end
turtle.digDown()
if (not turtle.down()) then
error("NO se logro romper bloque")
end
global_deltah=global_deltah-1
end
-- Funcion que retorna a origen dado desplazamiento global
function retorno()
printf("El delta de posicion global_orientacion es \n")
printf("DH: %d DW: %d DD: %d global_orientacion: %d \n",global_deltah,global_deltaw,global_deltad,global_orientacion)
-- Ajusta global_orientacion
local dh = global_deltah
local dw = global_deltaw
local dd = global_deltad
-- Primero ajusta dH
for i=1,math.abs(dh) do
if (dh > 0) then
down()
else
up()
end
end
--Ajusta DW
while (global_orientacion ~= 1) do
tLeft()
end
for i=1,math.abs(dw) do
if (dw > 0) then
back()
else
forward()
end
end
-- Ajusta dD
while (global_orientacion ~= 0) do
tLeft()
end
for i=1,math.abs(dd) do
if (dd > 0) then
back()
else
forward()
end
end
printf("Posterior a relocacion GLOBALES \n")
printf("DH: %d DW: %d DD: %d global_orientacion: %d \n",global_deltah,global_deltaw,global_deltad,global_orientacion)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment