Activity: Turtle 🐢

In Thonny create a file named turtle-demo.py with the following content. Save it in the folder CS100/ch1.

  1. Run this program and match the output with your code. Understand each instruction is doing.

    import turtle
    
    t= turtle.Turtle()
    
    print( "Orig. pos: ", t.position() )
    
  2. Note the original position of the turtle in a coordinate system.

Add the following code to the end of the program:

   
   t.forward(300)
   t.penup()
   t.left(90)
   t.forward(50)
   t.left(90)
   t.pendown()
   t.forward(300)

Note: Penup lifts the drawing pen so the turtle does not leave a trail. Pen down lowers the drawing pen so that the turtle leaves a trail again.

  1. Using the color commands (i.e. t.pencolor(‘red’)) modify your program so that it draws the top line in red, and the bottom line in blue.

  2. Using the width command (i.e. t.width(10)) modify your program so that it draws the top line at width 10 and the bottom line at width 5.

  3. Write additional commands to draw a green square around the outer edge of the drawing space very close to the edge. To do this you will have to experiment to find the coordinates of the edges of the drawing canvas.

  4. In addition to movement of the turtle through the forward command and the right and left command, you can also move the turtle directly to a location using the t.goto(x,y) command. Draw a 300, 400, 500 right triangle (cyan in color) with one vertex at the origin - location (0,0). This is very difficult to do with the forward and turn commands, but easier to do with the goto command.

After all the commands have been done correctly, your picture should look like this:

Turtle Graphics Results

All of the commands for the turtle graphics (forward, turn, goto, etc.) are functions. They are built-in and part of the turtle library that we included when we did the import. Now, we’ll write our own graphical function that collects several drawing commands together. Add the following code to the bottom of your program:


def drawRightTriangle():
	x = t.xcor()
	y = t.ycor()
	t.setheading(0)
	t.pendown()
	t.forward(90)
	t.right(90)
	t.forward(120)
	t.goto(x,y)

Then, below that, add the commands:


t.penup()
t.goto(-100, 100)
t.pencolor("magenta")
drawRightTriangle()

Now add commands to the program to draw many triangles on the screen in different colors and locations.

How to submit

Make sure you saved your work and that it runs without errors. Submit your turtle-demo.py file to Moodle.

Optional: if you have extra time

Create a new file called turtle-extra.py and save it to your cs100/ch1 folder.

In the program draw a stick-figure type scene of your own design. A house? A car? A tree? You decide.