From c7cbc401596515404b0e857c10ab4b1aac447e6e Mon Sep 17 00:00:00 2001 From: Sascha Martens Date: Mon, 9 Nov 2020 20:45:05 +0100 Subject: [PATCH] Created modules.lua, added functions to it --- Modules/modules.lua | 104 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) create mode 100644 Modules/modules.lua diff --git a/Modules/modules.lua b/Modules/modules.lua new file mode 100644 index 0000000..f6d31b3 --- /dev/null +++ b/Modules/modules.lua @@ -0,0 +1,104 @@ +--[[Function Module program by Al Sweigart +Provides useful utility functions.]] + +-- selectItem() selects the inventory +-- slot with the named item, returns +-- true if found and false if not +function selectItem(name) +-- check all inventory slots + local item + for slot = 1, 16 do + item = turtle.getItemDetail(slot) + if item ~= nil and item['name'] == name then + turtle.select(slot) + return true + end + end + + return false -- couldn't find item +end + + +-- selectEmptySlot() selects inventory +-- slot that is empty, returns true if +-- found, false if no empty spaces +function selectEmptySlot() + + -- loop through all slots + for slot = 1, 16 do + if turtle.getItemCount(slot) == 0 then + turtle.select(slot) + return true + end + end + return false -- couldn't find empty space +end + +-- countInventory() returns the total +-- numer of items in the inventory +function countInventory() + local total = 0 + + for slot = 1, 16 do + total = total + turtle.getItem(slot) + end + return total +end + +-- selectAndPlaceDown() selects a nonempty slot +-- and places a block from it under the turtle +function selectAndPlaceDown() + for slot = 1, 16 do + if turtle.getItemCount(slot) > 0 then + turtle.select(slot) + turtle.placeDown() + return + end + end +end + + +-- buildWall() creates a wall stretching +-- in front of the turtle +function buildWall(length, height) + if modules.countInventory() > length * height then + return false --not enough block + end + + turtle.up() + + local movingForward = true + + for currentHeight = 1, height do + for currentLength = 1, length do + selectAndPlaceDown() -- Place the block + if movingForward and currentLength ~= length then + turtle.forward() + elseif not movingForward and currentLength ~= length then + turtle.back() + end + end + if currentHeight ~= height then + turtle.up() + end + movingForward = not movingForward + end + + -- done building wall; move to end position + if movingForward then + -- turtle is near the start position + for currentLength = 1, length do + turtle.forward() + end + else + -- turtle is near the end position + turtle.forward() + end + + -- move down to the ground + for currentHeight = 1, height do + turtle.down() + end + + return true +end