Now that our turtles can talk, let’s make them walk. Or even better, let’s make them dance! Although turtles come with a program called dance, it’s a simple program that only makes the turtles turn randomly. In this chapter, you’ll create a much better turtle dancing program. The steps will look like Figure 4-1.
Figure 4-1: The turtle’s dance steps
Using the text editor, create a program named mydance by entering edit mydance in the command shell. In the text editor, enter the following lines of code. Remember not to type the line numbers because they’re just for reference.
mydance
1. --[[Dance program by Al Sweigart
2. Make the turtle dance!]]
3.
4. print('Time to dance!')
5.
6. -- Turtle starts dancing
7. turtle.forward()
8. turtle.back()
9. turtle.turnRight()
10. turtle.forward()
11. turtle.back()
12. turtle.back()
13. turtle.turnLeft()
14. turtle.turnLeft()
15. turtle.back()
16. turtle.turnRight()
17.
18. -- Turtle spins around
19. for i = 1, 4 do
20. turtle.turnRight()
21. end
22.
23. turtle.up()
24. turtle.down()
25. print('Done.')
After you’ve entered all these instructions, save the program by pressing the CTRL button, making sure [Save] is selected, and pressing ENTER. Then quit the editor by pressing CTRL, selecting [Exit], and pressing ENTER.
After exiting the editor, run the mydance program in the command shell:
> mydance
Time to dance!
Done.
The text Time to dance! will appear onscreen. When the robot is done dancing, the text Done. will appear. Press ESC immediately after you run the program and before the text Done. appears to watch the turtle do a little dance. Every step the turtle takes is one that you programmed! Figure 4-2 shows how the turtle moves in response to the turtle.forward() and turtle.back() function calls on lines 7 and 8.
Figure 4-2: The turtle’s first two dance moves
Let’s look at each instruction in the mydance program.
The first two lines in the program contain a comment. Lua ignores comments because they’re just notes for the programmer. This comment describes what the program does and who wrote the program.
mydance
1. --[[Dance program by Al Sweigart
2. Make the turtle dance!]]
3.
4. print('Time to dance!')
5.
6. -- Turtle starts dancing
The comment in this program that begins on line 1 and continues on line 2 is a multiline comment because it extends beyond one line. Multiline comments begin with --[[ and continue until a ]] appears.
Line 4 calls the print() function and makes Time to dance! appear in the command shell when you run the program. You learned about the print() function in Chapter 3.
Line 6 is also a comment, but it’s a single-line comment. The comment starts at -- and ends at the end of the line instead of spanning multiple lines. Lua ignores the Turtle starts dancing text, which describes what the code that follows line 6 does, because it’s a note for whoever is reading the program.
After line 6, the next several lines of code in mydance call functions that make the turtle move.
mydance
6. -- Turtle starts dancing
7. turtle.forward()
8. turtle.back()
9. turtle.turnRight()
10. turtle.forward()
11. turtle.back()
12. turtle.back()
13. turtle.turnLeft()
14. turtle.turnLeft()
15. turtle.back()
16. turtle.turnRight()
You learned about the turtle.turnLeft() and turtle.turnRight() functions in Chapter 2. There are four other functions for moving the turtle that you haven’t seen yet: turtle.up(), turtle.down(), turtle.forward(), and turtle.back().
Let’s experiment with these movement functions in the Lua shell. Make sure you’re in the correct shell (the prompt will be lua> instead of >), and run the following instructions:
lua> turtle.up()
true
lua> turtle.down()
true
lua> turtle.forward()
true
lua> turtle.back()
true
Remember to include turtle. in front of the direction names, and be sure the turtle has fuel. The functions turtle.up() and turtle.down() move the turtle up into the air and back down toward the ground. The functions turtle.forward() and turtle.back() move the turtle forward in the direction it is currently facing and then backward in the opposite direction. You can see these movements in Figure 4-3.
Figure 4-3: Experimenting with the turtle’s movement functions
If the turtle is able to move in the direction you instruct it to, the function call will have a return value of true. (The values true and false are values of the Boolean data type, which I’ll explain in Chapter 5.)
With the turtle already on the ground, call the turtle.down() function in the Lua shell, like this:
lua> turtle.down()
false
Movement obstructed
Because a block is in the way, the turtle won’t be able to move, and the turtle.down() function call will return false and a string value that displays an error message. If the turtle is out of fuel, the movement will also fail, but a different message will be displayed:
lua> turtle.forward()
false
Out of fuel
These functions tell you the reason the turtle couldn’t move. You’ll call these movement functions often in this book’s programs to move the turtle.
So far, the mydance program’s execution, also known as the flow of execution, has started at the top of the source code and moved straight down, executing each line of code. However, we can make the execution loop over a group of instructions several times. Instructions that alter the normal line-by-line sequential flow of execution are called flow control statements.
Enter the following line of code into the Lua shell to see one type of flow control statement called the for loop:
lua> for i = 1, 4 do print(i) end
1
2
3
4
The instruction you entered is a for loop statement. A for loop can execute a group of instructions several times. This group, which is the code between the do and end keywords, is called a block, and each execution of the block is called an iteration. The block in the example is made up of the print(i) function call. (Programmers often use the variable name i in for loops. It stands for “iteration.”) A block can be made up of several lines of code, but in this case the block is simple and has just one function call. This for loop tells Lua to execute this block four times because the 1, 4 tells the loop to iterate from 1 to 4.
The statement for i = 1, 4 do print(i) end prints the numbers 1 to 4. The first time Lua executes the code in the block, the i variable is set to 1, which evaluates to print(1), displaying 1 on the screen. This is the first iteration of the for loop. When the execution reaches the end of the code in the block, it moves back up to the start of the block to run the code a second time. On this second iteration, 1 is added to the i variable so it’s set to 2, and 2 is printed to the screen. The execution continues to loop until i is set to 4 on the fourth and final iteration, which is the number after the comma in the for loop statement.
We can supply any two numbers to the for loop. For example, enter the following into the Lua shell to make a for loop iterate from 10 to 13:
lua> for i = 10, 13 do print(i) end
10
11
12
13
We can also specify a third number, which is called the step number. Instead of increasing by 1 after each iteration, we can make the for loop increase or decrease the loop’s variable by any amount. Enter the following into the Lua shell:
lua> for i = 10, 20, 2 do print(i) end
10
12
14
16
18
20
This line of code makes the step number 2, so Lua will print all the even numbers between 10 and 20.
We can also use negative numbers in a for loop to make the loop count down from the starting number. In the following line of code, we use a step number of -1:
lua> for i = 4, 1, -1 do print(i) end
4
3
2
1
This code makes the for loop count down from 4 to 1. Try changing the step number to -2 to see what happens. Using for loops is a simple way to execute a group of instructions multiple times. You’ll learn other flow control statements in Chapter 5.
Let’s return to the mydance program. Lines 19 to 21 use a for loop to make the turtle spin:
mydance
18. -- Turtle spins around
19. for i = 1, 4 do
20. turtle.turnRight()
21. end
When we use for loops in programs, it’s common to indent (that is, add spaces to the beginning of) each line of code in the loop’s block. Indenting code lines makes it easier to see which lines are inside which blocks, especially when you start adding blocks inside other blocks (we’ll do this in Chapter 5). The end keyword is at the same level of indentation as the for keyword, making it easy to see where the loop begins and ends.
Line 20, which turns the turtle to the right, executes four times, making the turtle do a complete 360 degree spin. If you changed line 19 to for i = 1, 8 do, you could make the turtle perform two complete spins like in Figure 4-4.
Figure 4-4: A turtle does two spins by turning right eight times.
Finally, in lines 23 and 24, the turtle will do a little hop by moving up and then back down:
mydance
23. turtle.up()
24. turtle.down()
25. print('Done.')
This hop looks like Figure 4-5. The last line of the program prints Done., and because there’s no more code after line 25, the program terminates.
Figure 4-5: The turtle does a hop when turtle.up() and turtle.down() are called.
After you’ve entered your program into the turtle, you might want to share it with your friends. To copy programs from your turtle to the internet, you can use a pastebin website where people share text online by copying and pasting it to the website. You can upload your turtle programs as text to https://pastebin.com/, a popular pastebin site, by using the pastebin program that comes with all turtles. Enter the following into the command shell to upload mydance:
> pastebin put mydance
Connecting to pastebin.com... Success.
Uploaded as
https://pastebin.com/BLCJbpQJ
Run "pastebin get BLCJbpQJ" to download
anywhere
After uploading the program, the https://pastebin.com/ website will generate a new, unique web address for it. When I ran the pastebin program, it told me the mydance program was successfully uploaded to https://pastebin.com/BLCJbpQJ/. Now anyone can see this program by opening a web browser to that site. You can also download this program to your turtle by entering the following into the command shell:
> pastebin get BLCJbpQJ mydance
Connecting to pastebin.com... Success.
Downloaded as mydance
The get BLCJbpQJ mydance command line argument tells pastebin that you want to get the program at https://pastebin.com/BLCJbpQJ/ and save it on the turtle as mydance. Now you have a way to upload and download files to share them with others.
If the pastebin program displays the message Connecting to pastebin.com... Failed. when you run it, double-check that you typed the command line argument (BLCJbpQJ or whatever address was assigned to your pastebin) correctly and that you’re connected to the internet. If the pastebin program displays File already exists, you need to first delete the existing mydance program, which is covered next.
When you ran the pastebin program, you told it to download the file, save it on the turtle, and name the file mydance. But if a program already exists with this name (such as the one you created with edit mydance), you’ll either need to choose a different name or delete the existing mydance program.
To delete a program off the turtle, run the delete command followed by the name of the program to delete. For example, enter the following into the command shell:
> delete mydance
This line deletes the mydance program. Now you can run pastebin get BLCJbpQJ mydance to download the program from the internet.
Keep in mind that for each Minecraft server, the https://pastebin.com/ website allows only 25 new “pastes” per day. This limitation can make it difficult to update pastes with new changes to your programs if lots of players are on your server.
You can also share your programs online without limitations at https://turtleappstore.com/. Instead of using the pastebin program, you can use the appstore program. Download the appstore program by running pastebin get iXRkjNsG appstore in the command shell:
> pastebin get iXRkjNsG appstore
Connecting to pastebin.com... Success.
Downloaded as appstore
The appstore program will download programs to your turtle just like the pastebin program does. For example, you can run appstore get AlSweigart mydance to download the mydance program from the AlSweigart appstore on the https://turtleappstore.com/ website.
To upload your programs to the appstore and browse programs others have made, go to the https://turtleappstore.com/ website and sign up for a free account. You’ll find programs written by others, and you can learn from their code! This website also contains all the programs in this book.
In this chapter, you learned several new programming concepts. You learned how to use comments to make notes that Lua will ignore. These comments can serve as reminders or describe what different parts of your program do. Single-line comments begin with --, and multiline comments begin with --[[ and end with ]].
You learned how to move the turtle with the movement functions: turtle.forward(), turtle.back(), turtle.turnLeft(), turtle.turnRight(), turtle.up(), and turtle.down().
This chapter covered a new type of flow control statement called the for loop. These loops let you execute the same block of code a certain number of times.
You can use the pastebin program that comes with ComputerCraft turtles to share programs online at https://pastebin.com/. The appstore program at https://turtleappstore.com/ provides some additional features as well.
In Chapter 5, we’ll expand on the mydance program and use some new flow control statements, data types, and operators. With this knowledge, you’ll be ready to automate Minecraft chores with turtles!