Welcome! In this blog post, we will be breaking down a Lua program that utilizes a ComputerCraft Turtle to harvest crops in a farm.
We will build the program step by step to make it easy to understand for beginners.
To begin with, the program takes in two user inputs, x and z, which represent the dimensions of the farm. x is the length of the farm, while z is the width.
lua
local x,z = …
Next, the program subtracts 1 from the x dimension.
This is because the Turtle needs to move along the rows of crops and it will be starting at the first block of the first row.
If we don’t subtract 1, the Turtle will move one block past the last row of crops.
lua
x = x-1
Now, let’s look at the detectHarvest function. This function is used to detect if the crop is ready to harvest or not.
If the age of the plant is 7, then it is ready to be harvested.
lua
local function detectHarvest()
local status,detect = turtle.inspectDown()
if type(detect) == “table” then
if detect.state.age == 7 then
turtle.digDown()
turtle.placeDown()
end
end
end
The turtle.inspectDown() function is used to detect the block below the Turtle. If the block is a crop, then the function returns the properties of the crop in the detect variable.
The type() function is used to check if the detect variable is a table.
If it is a table, then we can check the age property of the crop.
If the age is 4, then the Turtle will harvest the crop by using the turtle.digDown() function to break the block and the turtle.placeDown() function to plant a new crop.
Moving on to the main for loops, this is where the Turtle will move around the farm and harvest crops.
The outer for loop will iterate z times, which is the length of the farm.
lua
for currentZ = 1, z do
The first if statement checks if the current z position is odd or even.
This is done to determine which direction the Turtle needs to turn after moving along a row of crops.
scss
if currentZ % 2 == 1 and currentZ ~= 1 then
turtle.turnLeft()
turtle.forward()
turtle.turnLeft()
elseif currentZ % 2 == 0 and currentZ ~= 1 then
turtle.turnRight()
turtle.forward()
turtle.turnRight()
end
If the current z position is odd, the Turtle will turn left, move forward, and turn left again.
If it’s even, the Turtle will turn right, move forward, and turn right again.
The turtle.forward() function is used to move the Turtle along a row of crops.
Finally, the inner for loop will iterate x times, which is the width of the farm.
Within this loop, the detectHarvest() function is called to check if the crop is ready to be harvested.
If it is, the Turtle will harvest the crop.
lua
for currentX = 1, x do
detectHarvest()
turtle.forward()
end
And that’s it! We have successfully built a Lua program that utilizes a ComputerCraft Turtle to harvest crops in a farm.
This program is a great example of how programming can automate repetitive tasks and save time and effort.