Conditionals and loops

Detect and Inspect

These three instructions are useful to decide what or if there is a block near the turtle.

The detect command detects if there is an existing block ahead, up or below the turtle. If there is not, the turtle can move. Else, you may use the dig command to destroy the block.

The following program will make the turtle move 10 blocks. If there is an obstacle, the turtle will destroy it.

The rep command stands for repeat.

Repeat is a block which must be written as following:

rep <number> do

<instructions>

end

Inside a repeat loop you can nest other instructions as well.

In the next example the turtle will check 10 times if there is a block ahead; if it is true, it will break the block; in any case it will move 10 blocks forward.

The if statement is a conditional. It is checked once. If it is true it will execute whatever inside the command. An if statement must be written as following:

if <condition> then

<instructions>

end

The next program is an example of the inspect block. While the turtle inspects the block ahead and it is not a block of cobblestone, the turtle moves.

The turtle will stop moving when face a cobblestone block.

The while loop is the second iterative control statement.

A while loop must be written as following:

while <condition> do

<instructions>

end

In the while loop the instructions inside are executed as long as the condition is true. The moment the condition turns false there will be an exit from the loop.

In a repeat loop you must state in advance the number of repetitions. In a while loop this number is unknown as the condition may turn false at any point.

Build a bridge with the while loop

The following code will make the turtle build a bridge, provided that the turtle moves in the air.

In particular, the turtle detects if there is a block below.

If not, the turtle places a block from the first slot of its inventory.

It is required that there are some block items (stone or dirt etc) in the turtle’s inventory.

A fully functional program is the following.

The turtle will keep moving until detects a block.

If below the turtle is nothing, a block will be placed.

This way the turtle will build a bridge while walking in the air.

Of course, if there is nothing ahead the turtle will keep moving forward forever.

 

 

 

Download the lesson in pdf

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.