CPSC 120: Principles of Computer Science
Fall 2002

Lab 5: xTurtle Basics



THIS LAB is an introduction to a high-level programming language called xTurtle. This language was created to be used with The Most Complex Machine, but it is in the mainstream of high-level languages, along with Pascal, Ada and C. It incorporates some ideas common to all these languages, such as variables, assignment statements, loops, if statements and subroutines. (You should find that you are already familiar with the basic ideas because of your work in previous labs.) The xTurtle language also contains special-purpose commands for doing turtle graphics. These commands can be used to draw pictures on the computer screen. In this lab, you will learn about the basic xTurtle commands, about loops and if statements, and about variables. Future labs will cover programming in more detail, including the use of subroutines.

This lab covers some of the same material as Chapter 6 of The Most Complex Machine. The lab is meant as a self-contained introduction to this material, but it would still be useful to read Chapter 6, Sections 1 and 2, before doing the lab.

The exercises for this lab ask you to save some files in the "homework" directory in your Linux account. Under Windows, make sure that your math account is mounted as a network drive. Goto the Lab5 folder in the cpsc120 folder and double-click the icon named "Run xTurtle Lab5". Assuming that your math account has been mounted, you will be able to directly save files into your homework directory. Please be sure to give your files obvious names, or make a sub-folder for them inside the homework folder.

You can also run xTurtle off the web by clicking the following button. However, if you do this , you will not be able to save your work:

(Sorry, your browser doesn't do Java!)


Basic xTurtle Commands

When the xTurtle applet first starts up, it displays a white drawing area on the left, with a strip of controls on the right. There is a "turtle" in the center of the drawing area, represented as a small black triangle. The turtle has a position and a heading. Its heading is the direction it is facing, given as a number of degrees between -180 and 180. The turtle has a heading of zero when it is facing to the right, a heading of 90 when it is facing upwards towards the top of the screen, and a heading of -90 when it is facing downwards. Its position is given by two numbers: an xcoord, or horizontal coordinate, and a ycoord, or vertical coordinate.

The drawing area of the applet includes a twenty-by-twenty square in which the turtle can move and draw. This square has horizontal coordinates from -10 on the left to 10 on the right, and it has vertical coordinates from -10 at the bottom to 10 at the top. Because the drawing area is unlikely to be exactly square, the coordinates for the entire drawing area probably extend beyond the range -10 to 10 in either the horizontal or vertical direction.

The turtle starts out in the center of the screen -- at the point (0,0) -- facing to the right. It can obey commands such as "forward(5)," which tells it to move forward five units, and "turn(120)," which tells it to rotate in place through an angle of 120 degrees. (It turns counterclockwise if the number of degrees in positive and clockwise if the number of degrees is negative.) The number in parentheses is called a parameter for the command; you can substitute any number you want. The parameter in a "forward" command tells the turtle how far to move forward, while the parameter in the "turn" command tells it how many degrees to turn.

The turtle can draw a line as it moves. You can think of it as dragging a pen that draws as the turtle moves. The command "PenUp" tells the turtle to "raise the pen." While the pen is raised, the turtle will move without drawing anything. The command "PenDown" tells the turtle to lower the pen again.

Just below the drawing area of the applet are a text-input box and a button labeled "Do It". You can type commands for the turtle in the text-input box. When you press return or click on the "Do It" button, the turtle will carry out the command or commands that you typed. You can type in several commands at once, or you can type in one command at a time, pressing return after each command. Note also that after a command is executed, the contents of the text-input box are hilited, so that as soon as you start typing, the previous command will be erased and replaced with what you type. And finally, note that you can change the speed at which the turtle follows a sequence of commands by changing the setting of the Speed pop-up menu, which is one of the controls located to the right of the drawing area. (The speed is initially set to "Fast".)

You can use the command "clear" to clear the screen and the command "home" to return the turtle to its original position and orientation (at the center of the screen, facing right).

The turtle can execute a number of other commands, in addition to forward, turn, PenUp, PenDown, clear, and home. Here are a few more basic commands. In this list, x and y are parameters. You can replace a parameter with a number when you use the command.

Draw some pictures using these basic commands. Here are a few things you can try, for example:


Color

Unless you tell it to do otherwise, the turtle will draw everything in red. However, you can tell it to change its drawing color to any other color. The turtle understands the following basic color commands: red, blue, green, cyan, magenta, yellow, black, white, and gray. After it executes one of these commands, it will draw in the specified color until it comes to another color-change command. For example, the following sequence of commands will draw a triangle with each side in a different color:

            green forward(5) turn(120)
            blue  forward(5) turn(120)
            cyan  forward(5) turn(120)

Besides these basic color commands, there are two commands that can be used to specify any drawing color that the computer is capable of displaying. The commands are rgb(x,y,z) and hsb(x,y,z), where x, y, and z are parameters that can have any value in the range 0.0 to 1.0. To understand these commands, you need to know something about color. (But you can safely skip the details, if you want.)

Any color can be specified as some combination of the primary colors, red, green, and blue. In the command rgb(x,y,z), the parameters x, y, and z specify the amount of red, green, and blue in the color. For example, a value of zero for x indicates that the color is to contain no red at all, and a value of one for x means that the color contains the maximum possible amount of red. So, rgb(0,0,0) represents black, rgb(1,0,0) represents bright red, and rgb(0.5,0,0) is a darker red. Some other examples: rgb(0.8,0.8,0.8) is a very light gray, rgb(1,0.6,0.6) is pink, and rgb(0,0.4,0.4) is a dark blue-green.

The command hsb(x,y,z) uses an alternative method of specifying a color. In this command, x, y, and z represent hue, saturation, and brightness. The hue is the basic color: As x ranges from zero to one, the hue ranges through the spectrum from red through orange, yellow, green blue, violet, and back to red. The meaning of the brightness parameter is pretty clear, with a value of one representing the brightest color of a given shade. The saturation can be thought of as follows: A saturation value of one gives the purest possible version of a color. Decreasing the saturation from one towards zero is like mixing paint of that color with gray paint of equal brightness. The basic color remains the same, but it becomes "diluted."

You'll find some examples of using the rgb and hsb commands later in the lab.


Writing xTurtle Programs

The power of a computer comes from its ability to execute programs. The xTurtle applet allows you to write and run programs. Programs can include all the basic commands described above. They can also include loops, decisions, subroutines, and other features.

The applet can be configured to load one or more programs when it starts up. The applet that you launched with the button above should have loaded several sample programs that you will use in this lab. You can also write new programs from scratch. You can select among the programs that the applet knows about using the pop-up menu at the very top of the applet. You can begin a new program by clicking on the "New Program" button, or by choosing "[New]" from the pop-up menu. (There are also buttons for loading programs from files and for saving programs to files; however, the configuration of your Web browser might prevent these buttons from functioning.)

One of the sample programs for this lab is called "Fan.txt". Select this program from the pop-up menu at the top of the xTurtle applet. This program contains an example of a loop. The program itself reads:

       
       LOOP
           forward(5)
           back(5)
           turn(3)
           EXIT IF heading = 0
       END LOOP

In addition to these commands, the program contains comments. A comment is anything enclosed between braces, { and }. Comments are meant for human readers of the program and are completely ignored by the computer. You should read the comments on any program to help you understand what it does and how it works.

In an xTurtle program, a loop consists of the word loop, then a sequence of instructions, then the words end loop. One of the instructions must be an exit statement, which gives a condition for ending the loop. In the sample program, the statement "exit if heading = 0" includes the condition "heading = 0. Since the heading is the direction that the turtle is facing, this condition is true when the turtle is facing in the direction zero (that is, directly towards the right).

When a loop is executed, the computer will execute the statements in the loop repeatedly. Each time the exit statement is executed, the computer tests the condition specified by that statement. If the condition is satisfied, the computer jumps out of the loop. (Ordinarily, after exiting from a loop, the computer jumps to the statement that follows the end loop. In this example, there is no further statement after the loop, so the program ends when the loop ends.)

To run a program in the xTurtle program, select it from the pop-up menu if necessary, so it is visible on the screen. Then click on the "Run Program" button. If there are no errors in the program, the computer will switch back to the drawing area and execute the program. You can control the rate of execution with the speed pop-up menu. You can pause the execution with the "Pause" button, and you can terminate it permanently with the "Stop" button. After the program has been executed, you can run it again by clicking the "Run Program" button. Note that every time you run a program, the turtle starts out in its initial configuration: at the center of the drawing area, facing right, with the pen down, and with the drawing color set to red.

Run the "Fan" program, and try to understand how it works. As another example, modify Fan.txt so that it changes color as it draws:

         DECLARE hue
         hue := 0
         LOOP
            hsb(hue,1,1)
            forward(5)
            back(5)
            turn(3)
            hue := hue + 1/120
            exit if heading = 0
         END LOOP

This program uses a variable named "hue". (You can use any names you want for variables, as long as you avoid words that already have a special meaning, such as "loop" and "if".) A variable is just a memory location which has been give a name and which can be used to store a value. In xTurtle, you give a name to a memory location with a declare statement. Once you have declared a variable, you can store a value in it with an assignment statement, which has the form

           <variable-name>  :=  <value>

The operator := is called the assignment operator. It tells the computer to calculate the value on the right and to store it into the variable on the left. The value on the right can be given as a number, as another variable, or as a mathematical formula. For example:

           hue := hue + 1/120
           x := 17
           newAmount := oldAmount
           cost := length * width * costPerSquareFoot

For a prettier picture, try adding the command circle(2) between the forward(5) and back(5) statements in this program.


Next, we turn to an example that introduces the if statement. This is the sample program "RandomWalk.txt", which should already be loaded into the xTurtle applet. Select the "RandomWalk" program from the pop-up menu and run the program several times. This program makes the turtle do a "random walk" in which it repeatedly moves in a randomly chosen direction. Read the program and the comments on it, and try to understand how it works.

In particular, look at the if statement in the Random Walk program. An if statement is used to decide among alternative courses of action. An if statement begins with the word if and ends with the words end if. (The "end if" here is not a separate command; it is merely a required syntactic marker to mark the end of the if statement. It is very different from an "exit if" statement, and you should try not to confuse them.) The exact rules for using if statements are rather complicated, and are covered in The Most Complex Machine and in the detailed on-line information about xTurtle. However, you should be able to get the basic idea by looking at the example in the sample program.


Interacting with the User

Any real programming language needs to provide some way for a program to communicate with the person who is using the program. The xTurtle programming language provides only minimal support for input and output, but what it provides is enough for a program to have a simple dialog with the user.

There are two commands for output (sending information from the computer to the user), and one command for input (getting information from the user into the computer). All of these commands use strings. A string is sequences of characters enclosed in quotes, such as: "Hello". The command

               DrawText("Hello")

will print the string Hello in the drawing area at the current turtle position. (Note that the quotes are not of the string that is displayed. The quotes are just there in the program to tell the computer that this is a string.)

The command

               TellUser("Hello")

will display {\tt Hello} in a little green-colored box in the center of the display area. There will also be a button labeled "OK". The user reads the string and then clicks on the OK button to get rid of the box. The TellUser command has no permanent effect on the picture in the drawing area.

Finally, there is the more complicated input command, AskUser. This command allows the user to enter a number; the number entered by the user will be stored in a variable. The variable must, of course, be declared before it can be used in this command. For example, assuming that a variable named "betAmount" has been declared, the command

               AskUser("How much do you want to bet?", betAmount)

will display a box containing the string "How much do you want to bet?" along with a text-input box where the user can enter a response. The number entered by the user will be stored in the variable betAmount, and the program can then use that number by referring to the variable.

All of the input/output commands have a nice feature that allows you to include the value of a variable in a string. If a string includes the special character #, then that # must be followed by the name of a variable. When the string is displayed, the # and the name will be replaced by the value of the variable. For example, if betAmount and winnings are variables with the values 25 and 75, then

              TellUser("You bet #betAmount dollars; you win $#winnings.")

would display the string: You bet 25 dollars; you win $75.

All of this is illustrated in the sample program "InputOutputExample". You should select this program from the pop-up menu, read it, run it, and try to understand it.


Exercises

These exercises are due next Friday, October 18. For Exercises 1, 3, and 4, you should save a program in your homework directory. In the lab report that you turn in, you should tell me the file names for your programs, and if you are working with someone, you should tell me whose directory to look in to find the program. You should turn in your answers to Exercises 2, 5, and 6 on paper.


Exercise 1: Find a sequence of xTurtle commands to draw each of the following: a square with a circle inside it; a pair of lines connected by half-circles at each end; a plus sign. The pictures should look something like this:

Write a program that includes commands for drawing all of these figures. Use PenUp, moveTo, and PenDown to move from one figure to the next without drawing a line.


Exercise 2: The following program was used as an example earlier in the lab. It draws 120 lines radiating out from a central point. Each line is drawn with a different "hue,", and the colors of the lines range throughout the entire spectrum.

         DECLARE hue
         hue := 0
         LOOP
            hsb(hue,1,1)
            forward(5)
            back(5)
            turn(3)
            hue := hue + 1/120
            exit if heading = 0
         END LOOP

The word random can be used in a program to represent a random value in the range from 0.0 to 1.0. (Random is actually a function with no parameters, but it acts like a variable that has a different value each time it is used.) What happens if you substitute the command hsb(random,1,1) for the command hsb(hue,1,1) in this program? What happens if you substitute the command rgb(random,random,random) for the command hsb(hue,1,1)? Why? Explain carefully what the modified programs do. Do you need the variable hue in the modified programs?


random circle walk Exercise 3: Modify the "RandomWalk" sample program in two ways. First, add a command that will make it choose a different, random color each time through the loop. If you run the program after making this modification, each line in the random walk will be randomly colored. The second modification will make the program draw random arcs instead of randomly directed lines. In the original program, the computer chooses one of four directions at random. Modify it so that it chooses one of the following three commands at random: arc(0.3,90) or arc(0.3,180) or arc(0.3,270). The program should not draw the straight line. The picture produced by the program will be similar to the design shown at the right. Save a copy of your program in your homework directory.


Exercise 4: With what you have learned in this lab, you can write a simple guessing game program (which will use none of the graphical capabilities of xTurtle). Write a program in which the computer chooses a random integer between 1 and 100, and the user tries to guess the number. Each time the user makes a guess, the computer should (honestly) tell the user "Sorry, your guess is too high," "Sorry, your guess is too low" or "You got it." Although this program does something completely different from the random walk sample program, nevertheless it is similar in general outline. In particular, you will use an if statement inside a loop. Use a loop to allow for repeated guesses. The loop will end when the user guesses correctly. Your program can begin the following three lines, before the loop:

        DECLARE answer
        DECLARE guess
        answer := randomInt(100)

Your program should include comments to explain what it does. Like the sample programs, it should use indentation to show the structure of the program. (The "Indent" button can be used to automatically indent a program; this feature is also useful for finding certain types of errors in a program, such as a missing end if.)

(If you get the basic game to work correctly, you can do the following for a little extra credit: Improve the guessing game program so that after each game, it will give the user the option of playing again. You will need to add another loop to the program, containing the loop that already exists. You will also need to know a new command. The YesOrNo command can be used to ask the user a yes-or-no question. Specifically, if response is the name of a variable, then the command

           YesOrNo("Do you want to play another game?", response)

will ask the user the given question. It will store a 0 in the variable response if the user answers no and will store a 1 in that variable if the user answers yes. The outer loop should continue until the value of the response is 0.)


Exercise 5: You have probably already discovered that the computer can display error messages if you try to run a program that contains an error. Errors that the computer can find before actually running the program are called syntax errors. The following program contains several syntax errors. Find each error and explain what is wrong in each case. (You can type in the program and let the computer find the errors.)

          DECLARE length
          length = 8
          LOOP
             forward length
             turn(90)
             length := length - 1
             EXIT IF length equals 0
          END LOOP

Some errors can only be found when a program is running. For example, what error occurs when the following program is run? (Type it in and find out!)

        DECLARE sum, count
        sum := 0
        count := 0
        LOOP
           sum := sum + 1/count
           count := count + 1
           EXIT IF count = 10
        END LOOP
        DrawText("The sum is #sum.")

There is a third -- and much worse -- type of error, which occurs when the program gives an incorrect result but the computer gives you no warning of the fact that the answer is wrong. Give an example of such an error. Explain why the computer cannot detect such "wrong-answer errors."


Exercise 6: This exercise assumes that you are familiar with the "xComputer" model computer, which is used in some other labs. Write a short essay comparing the assembly language of xComputer with the high-level programming language, xTurtle. For example, you could: compare the way loops are constructed in each language; compare labels in assembly language to variables in xTurtle; and compare the way computations are done in assembly language with the way they are done by assignment statements in xTurtle.


(David J. Eck, eck@hws.edu)