sCCripts/jlib/fuel.lua

116 lines
2.8 KiB
Lua
Raw Normal View History

2020-12-28 14:45:50 +01:00
-- Created by Jef Roosens
--
-- This module contains functions which ease fuel management in a turtle
-- local turtle = require('turtle')
local module = {}
module.logger = require("jlib.log").Logger:new{level = -1}
-- Refuel the turtle using the given slot; tries to optimize refuel speed by
-- calculating needed refuel count
--
-- @param slot slot to refuel from
-- @param goal refuel goal to reach
-- @return wether the refuel was enough
function module.refuel_from(slot, goal)
-- First, we get the current level
local start = turtle.getFuelLevel()
-- If we've already reached the goal, just return true
if start >= goal then return true end
-- Select the slot and refuel once
turtle.select(slot)
turtle.refuel(1)
-- Get the difference
local level = turtle.getFuelLevel()
local diff = level - start
-- If the diff is 0 the slot is empty or can't refuel, so return false
if diff == 0 then return false end
-- Calculate needed refuels
local needed = math.ceil((goal - level) / diff)
-- Do the refuel
turtle.refuel(needed)
-- Return wether or not we reached the goal
return turtle.getFuelLevel() >= goal
end
-- Check if the turtle has enough fuel; takes a table of preferred items
--
-- @param goal fuel goal to reach
-- @param preferred table containing names of preferred items
-- @return wether or not the fuel level was reached
function module.check(goal, preferred)
-- Convert table to set for faster lookup
local set = {}
if preferred then
for _, v in ipairs(preferred) do
set[v] = true
end
end
-- Turtle needs to be able to get down at all times
local i, done = 1, turtle.getFuelLevel() >= goal
-- Instantly quit if it's already good
-- This check is mostly useful voor the logging aspect
if done then
module.logger:info("No refuel needed.")
return true
end
-- Store all non-preferred options
local options = {}
-- Iterate over all 16 slots, or stop earlier if possible
while not done and i <= 16 do
local data = turtle.getItemDetail(i)
if data and set[data.name] then
done = module.refuel_from(i, goal)
else
table.insert(options, i)
end
i = i + 1
end
-- Exit if goal has been reached
if done then
module.logger:info("Refueled using preferred.")
return true
end
-- Process non-preferred options
for _, j in pairs(options) do
done = module.refuel_from(j, goal)
if done then
module.logger:info("Refueled using non-preferred.")
return true
end
end
module.logger:warning(
"Refuel failed. Missing: " .. goal - turtle.getFuelLevel())
return false
end
return module