DAY 28
0
Software Development

## Day28 小烏龜自動掘井挖隧道

excavate.lua 和 tunnel.lua
tunnel 是用來挖隧道用的，隧道寬度固定為 3 格，高度固定為 2 格，長度可自訂

``````tunnel 5
``````

``````local collected = 0

local function collect()
collected = collected + 1
if math.fmod(collected, 25) == 0 then
print("Mined " .. collected .. " items.")
end
end
``````

``````local function tryDig()
while turtle.detect() do
if turtle.dig() then
collect()
sleep(0.5)
else
return false
end
end
return true
end
``````

turtle.detect() 就是判斷前方是否可以挖，回傳 true / false，相關函數有 turtle.detectUp(), turtle.detectDown()
turtle.dig() 當然就是挖掘前面方塊了，回傳 true / false，相關函數有 turtle.digUp(), turtle.digDown()

``````local function refuel()
local fuelLevel = turtle.getFuelLevel()
if fuelLevel == "unlimited" or fuelLevel > 0 then
return
end

local function tryRefuel()
for n = 1, 16 do
if turtle.getItemCount(n) > 0 then
turtle.select(n)
if turtle.refuel(1) then
turtle.select(1)
return true
end
end
end
turtle.select(1)
return false
end

if not tryRefuel() then
while not tryRefuel() do
os.pullEvent("turtle_inventory")
end
print("Resuming Tunnel.")
end
end
``````

refuel 就是補充燃料了

turtle.select(n)

``````local function tryUp()
refuel()
while not turtle.up() do
if turtle.detectUp() then
if not tryDigUp() then
return false
end
elseif turtle.attackUp() then
collect()
else
sleep(0.5)
end
end
return true
end
``````

try 函數每次都先補充燃料確保可以動作

``````for n = 1, length do
turtle.placeDown()
tryDigUp()
turtle.turnLeft()
tryDig()
tryUp()
tryDig()
turtle.turnRight()
turtle.turnRight()
tryDig()
tryDown()
tryDig()
turtle.turnLeft()

if n < length then
tryDig()
if not tryForward() then
print("Aborting Tunnel.")
break
end
else
print("Tunnel complete.")
end

end
``````

turtle.placeDown() 一開始先在下方放置任意方塊，相關函數有 place(), placeUp()

### 小烏龜掘深井

tunnel.lua 是往前挖出隧道，excavate.lua 則是往下挖井，長寬為玩家自訂

``````excavate 3
``````

``````local function unload(_bKeepOneFuelStack)
for n = 1, 16 do
local nCount = turtle.getItemCount(n)
if nCount > 0 then
turtle.select(n)
local bDrop = true
if _bKeepOneFuelStack and turtle.refuel(0) then
bDrop = false
_bKeepOneFuelStack = false
end
if bDrop then
turtle.drop()
end
end
end
collected = 0
turtle.select(1)
end
``````

``````local function returnSupplies()
local x, y, z, xd, zd = xPos, depth, zPos, xDir, zDir
print("Returning to surface...")
goTo(0, 0, 0, 0, -1)

local fuelNeeded = 2 * (x + y + z) + 1
if not refuel(fuelNeeded) then
print("Waiting for fuel")
while not refuel(fuelNeeded) do
os.pullEvent("turtle_inventory")
end
else
end

print("Resuming mining...")
goTo(x, y, z, xd, zd)
end
``````

1. 燃料不夠
2. 儲物箱滿了（所以必須回到地面把東西吐出來）

goTo() 則很明顯是直接移動小烏龜到指定位置的函數，用的是相對座標
goTo(0, 0, 0, 0, 1) 便是回到一開始的位置和方向