Turtle Graphics Advanced

Turtle Graphics (A More In-depth Look)

The Python Turtle functions and methods can be used to do advanced Turtle Graphics programming. The Turtle Graphics Basic page introduced basic turtle graphics programming. 

Now we will take the next step and develop more advanced turtle graphics. The development of advanced graphics programs will build on the concepts from the Turtle Graphics Basic page. These programs build on the concepts such as for loops, while loops, functions, etc.

Below are a few graphics programs using the Python turtle module.

Turtle stamp() Function

The program below uses the stamp() function. The stamp() function leaves the trace (footprint) of the turtle as it moves across the screen. The for loop moves the turtle 30 pixels at a time in a pentagon shape. The turtle leaves a footprint of its position before it moves to the next position.

PROGRAM EXAMPLE: TURTLE MODULE stamp() FUNCTION

Program name: turtle_stamp.py

1  ###### PRINT TURTLE FOOTPRINT AS IT MOVES ######
2  # Use write() function to write a heading. 
3  import turtle
4  screen = turtle.Screen()
5  screen.setup(320, 320)   # Set Window size.
6  screen.title("Turtle Stamp") # Give a title to our screen.
7  screen.title("Turtle Stamp") 
8  
9  TTL = turtle.Turtle()
10  TTL.color("red")
11  TTL.shape("turtle")
12  TTL.hideturtle()
13  TTL.penup()
14  TTL.setposition(-50, -70)
15  
16  # Make the turtle move in a pentagon shape and leave a footprint of its path.
17  step = 30
18  for x in range(3):
19      # Leave a stamp of turtle's footprint on the screen after it has moved.
20      TTL.stamp()   
21      TTL.fd(step)
22      
23  TTL.lt(72)
24  for x in range(3):
25      TTL.stamp()
26      TTL.fd(step)
27  
28  TTL.lt(72)
29  for x in range(3):
30      TTL.stamp()
31      TTL.fd(step)
32  
33  TTL.lt(72)
34  for x in range(3):
35      TTL.stamp()
36      TTL.fd(step)
37  
38  TTL.lt(72)
39  for x in range(3):
40      TTL.stamp()
41      TTL.fd(step)
42  
43  TTL.setposition(-120, 100)
44  TTL.pencolor("blue")
45  TTL.write("TURTLE STAMP EXAMPLE", font = ("calibri", 18, "bold"))
46  
47  screen.exitonclick()

Detailed Line-by-line Explanation of the Program:

Line 3: import turtle

We need to import the turtle module as the first step.

Lines 4), 5), and 6) set up the turtle screen. Refer to the section on the Turtle Graphics Basic page.

Set-up Turtle Screen, Its Size and Screen Caption

Line 4: screen = turtle.Screen()

Use the Screen() function to name our screen. In this program, we name it “screen”. You can use any name you like.

Line 5: screen.setup(320, 320)

Use the setup(x,y) function to set up the screen size of width = 320 pixels and height = 320 pixels.

Code line 6): screen.title(“Turtle Stamp”)

“TurtleStamp” is the caption of the Turtle screen. It appears on the left-hand top of the screen window.

Select Turtle’s Name, Color, and Shape

Line 9): TTL=turtle.Turtle()

We define a variable “TTL”. The name of our turtle in this program is “TTL”.

Line 10): TTL.color(“red”)

The above line selects “red” as the color of the turtle.

Line 11): TTL.shape(“turtle”)

The above selects “turtle” as the shape of the turtle.

The turtle module supports many shapes for the turtle such as “arrow, “turtle”, etc. 

Set-up for Loop to Move the Turtle 30 Pixels, Leave a Footprint At Each Step. Repeat 3 Times

Lines 18), 20) and 21): for loop

Make the turtle move three steps. Each step is 30 pixels. The turtle leaves a footprint at each of the three positions.

Line 23: LEFT 72

Turn the turtle left by 72 degrees.

Lines 24 through 41: Repeat the same sequence as in lines 18 through 23 for a total of five times to make a pentagon shape.

Use write() Function to Write Text on the Screen

Lines 43) and 44): Move the turtle to a position, where the text “TURTLE STAMP EXAMPLE” will be written. Set the pen color to “blue”.

Line 45: TTL.write(“TURTLE STAMP EXAMPLE”, font = (“calibri”, 18, “bold”))

Write “TURTLE STAMP EXAMPLE: in Calibri font in bold, font size 18.

Line 47: screen.exitonclick()

Exit the program

The following is the image of the turtle’s footprints as the turtle moves on the screen in a pentagon shape.

Tyrtle Graphics Illustrare how stamp() Function Can Be Used to Leave the Turtle Footprint on the Screen
Turtle Graphics Stamp() Function

Turtle Stamp() Function to Draw a Spiral

The following example makes the turtle move in a spiral and leave a footprint. The turtle moves 25 steps.

At each step, the turtle moves by the number of pixels defined in the variable “step”. The turtle leaves its footprint at each position. After completing each step, the program increases the “step” variable by 2 pixels and turns the turtle right by 30 degrees.

PROGRAM EXAMPLE: TURTLE FUNCTION stamp() TO LEAVE A SPIRAL FOOTPRINT

Program Name: turtle_stamp_spiral.py

1  ###### PRINT TURTLE FOOTPRINT AS IT MOVES ######
2  # Use write() function to write a heading.
3  import turtle
4  # Set-up screen
5  screen = turtle.Screen()
6  turtle.setup(400, 400)
7  screen.title("Turtle Stamp Spiral")# Give a title to the screen. 
8  screen.bgcolor("cyan")
9  
10  # Set up Turtle properties
11  TTL = turtle.Turtle()
12  TTL.color("green")
13  TTL.shape("turtle")
14  TTL.hideturtle()
15  TTL.penup()
16  TTL.setposition(-20, 20)
17  
18  step = 20   # Define variable "step" and assign value = 20.
19  # The turtle moves by an amount = "step" at each iteration.
20  # Move the turtle 25 steps.
21  for i in range(25):
22      TTL.stamp()         # Print turtle footprint on the canvas.             
23      step = step + 2     # Increase the step size on every iteration by 2.
24      TTL.forward(step)   # Move turtle forward by amount = "step".          
25      TTL.right(30)       # Turn turtle by 30 degrees after each turtle step
26  
27  # The following code uses write() function to write "TURTLE STAMP SPIRAL".
28  TTL.setposition(-100, 150)
29  TTL.pencolor("blue")
30  TTL.write("TURTLE STAMP SPIRAL", font = ("calibri", 18, "bold"))
31  screen.exitonclick() # Exit the program if you click.

The program explanation is similar to turtle_stamp.py above.

The following is the spiral drawn by the turtle.

Turtle Graphics Turtle stamp() Function Usage to leave the turtle footprint.
Turtle Graphics Stamp() Function Usage to Leave a Footprint

Turtle Graphics Draw a Flower Using Circle() Function with for loop

The program below illustrates how you can use the setheading function to change the direction the turtle is facing.

We first set up the screen window size and name the window title (“25 CIRCLES FLOWER”) and select the pen color (“red”).

The program uses the turtle’s circle function to draw a circle with a radius of 50 pixels.

The program sets up a for loop to loop the code a total of 25 times from i = 0 to 24. In the for loop. It sets the turtle heading = 0 degrees.

After the loop corresponding to i = 0 completes for the first circle, the for loop executes the following instructions:

  • Increment the counting variable “i” by 1.
  • Increment the turtle’s heading by 15 degrees using myTTL.setheading(i*15) function.

The counting variable = 1 after the first loop. Therefore, the turtle heading is incremented by 15 degrees. Thus, the circle for the second loop will be turned by 15 degrees.

This process is repeated for all subsequent loops

PROGRAM EXAMPLE: TURTLE circle FUNCTION WITH for LOOP

Program Name: turtle_25_circles.py

1  # Draw 25 circles each with different headings
2  import turtle
3  screen=turtle.Screen() # set up window for turtle to play
4  screen.setup(320,320)
5  screen.title("25 CIRCLES FLOWER")
6  myTTL=turtle.Turtle()
7  myTTL.setheading(90)
8  myTTL.pencolor("red")
9  myTTL.speed(0)
10  
11  # for loop to draw circle 25 times
12  for i in range(0,25):
13      myTTL.penup()
14      myTTL.setpos(0, 0)
15      myTTL.pendown()
16  
17      myTTL.circle(50) # Radius of circle = 50 pixels
18      myTTL.penup()
19  # Increase the heading of the turtle by 15 degrees for each loop
20      myTTL.setheading(i*15)

The following is what the turtle drew.

Turtle Graphics Illustrate the Use of Turtle Module's circle() Function and setheading() Function
TURTLE MODULE’s CIRCLE() FUNCTION AND SETHEADING() FUNCTION USAGE

Turtle Graphics Draw a Flower Using for Loop With User Defined Function

This program is similar to the “turtle_25_circles_flower”.  Instead of the turtle’s circle function, we will use a square shape.

The program implements a for loop that iterates the for loop code 18 times. In each iteration of the for loop, the code draws a square.

The turtle heading is initialized to 0 degrees before the start of the first iteration.

After the completion of the first loop, the counting variable “i” is incremented by 1 and the turtle heading is incremented by 20 degrees. This process repeats for all successive loops.

Define User Defined Function

The Python Functions 2 chapter introduced the concept of user-defined functions.  The program creates a user-defined function called “square” with a parameter named “side”.

The for loop calls the function “square” and passes an argument “side” = 80.  Thus, the turtle will draw squares of side 80.

The turtle has a heading of 0 degrees for the square in the first loop. The squares in the successive loops are turned by 20 degrees relative to the squares in the previous loop.

PROGRAM EXAMPLE: TURTLE for LOOP WITH USER DEFINED FUNCTION

Program name: turtle_18_squares_flower

1  # Draw 18 squares each with different headings
2  import turtle
3  screen=turtle.Screen() # set up window for turtle to move around.
4  screen.setup(320,320)
5  screen.title("18 SQUARE FLOWER")
6  myTTL=turtle.Turtle()
7  myTTL.setheading(90) # Start with turtle pointing to 90 degrees (North).
8  myTTL.pencolor("red")
9  myTTL.speed(10)
10  ## Define 'square' function
11  def square(side):
12      for i in range(4):
13          myTTL.fd(side)
14          myTTL.rt(90)
15      
16  # for loop to draw square 18 times
17  for i in range(19):
18      myTTL.penup()
19      myTTL.setpos(0, 0)
20      myTTL.pendown()
21      # Call 'square' function.
22      square(80) # And pass the argument 'side' = 80
23      myTTL.penup()
24  # Increase the heading of the turtle by 20 degrees for each loop
25      myTTL.setheading(i*20)
26      

The following is program output.

Turtle Graphics How to Use Turtle Modules's Setheading() Function
Turtle Graphics Draw a Flower Using Setheading() function and User Defined Function

Turtle for Loop With List Data Type

Let us write another program using turtle.circle() function. The program makes use of the list data type. The items in the list select the color of the circles.

The program uses the for loop with the range() function to draw ten circles.

For each successive loop, the code selects the pen color from the list called “color_list” using the for loop counting variable “i”.  

The radius of the circle in the first loop is 20 pixels. The radius for each successive loop is calculated by multiplying 20 by (i+1).  Recall that the list index always starts at zero; this is why we use (i+1) as the multiplier for radius calculations.

PROGRAM EXAMPLE: TURTLE for LOOP WITH LIST DATA

Program name: turtle_circle_tangent_list

1  # Draw ten circles tangent to each other
2  # Use list data type to select the colors of the circles.
3  import turtle
4  screen=turtle.Screen()
5  screen.setup(480,320)
6  screen.title('TEN TANGENT CIRCLES')
7  TRTL=turtle.Turtle()
8  # Fefine color list data type 'color_list'.
9  color_list=['red','green','blue','black','purple']
10  for i in range(0,5):
11      TRTL.setpos(0, 0)
12      TRTL.hideturtle() # Let us hide turtle so it does not appear on the drawing.
13      TRTL.penup()
14      TRTL.pencolor(color_list[i]) 
15      TRTL.setheading(90)
16      TRTL.pendown()
17  #   If the radius is positive, circle is drawn clockwise.    
18      TRTL.circle(20*(i+1))
19      TRTL.pencolor(color_list[i])
20  #   If the radius is negative, circle is drawn counter-clockwise.
21      TRTL.circle(-20*(i+1))

The following is program’s output.

Turtle Graphics Draw Ten Circles of Different Colors Specified in a l=List Data Type
Turtle Graphics Draw Ten Circles of Different Colors Specified in a List Data Type

Turtle Module with while Function

The above two programs illustrate the use of for loop to draw interesting shapes using the turtle module. Let us now use the while loop to make a few graphics. 

The next program draws three-dimensional cubes.  First, we define a user-defined function “hexagon”.  The main program then calls the “hexagon” function inside the while loop that loops six times.

PROGRAM EXAMPLE: TURTLE MODULE WITH while LOOP

Program Name: turtle_while_loop_3-D_cubes

1  # while loop using hexagon user defined function.
2  import turtle
3  screen=turtle.Screen()  # set up window for turtle to move around.
4  screen.setup(320,320)   # Set up window size.
5  TRTL = turtle.Turtle()
6  screen.title("3-DIMENTIAL CUBES")
7  TRTL.penup()
8  TRTL.setposition(0,0)
9  TRTL.setheading(90)
10  TRTL.color('blue')
11  def hexagon():
12      for i in range(6):
13          TRTL.fd(50)
14          TRTL.rt(60)
15  # Set while loop counting variable 'i' = 1.
16  i = 1
17  while i < 7:
18      TRTL.pendown()
19  #   Call hexagon function.
20      hexagon()
21  #   After each hexagon is drawn, turn the turtle heading by 60 degrees.
22      TRTL.right(60)
23      i = i + 1 # Increase count variable 'i' by one and repeat while loop six times.

The following is the program output.

Turtle Graphics Draw a 3-D Cubes Using While Loop and User Defined Function.
Turtle Graphics Draw a 3-D Cubes Using While Loop and User Defined Function

For more information on Python Turtle graphics programming using for and while loops, refer to the link below:

<a href=”https://gist.github.com/joetechem/e5a213b8d44e8c6ca71fd8224ac64df3“>

Python Turtle Module and LOGO Together

We learned to do simple turtle graphics using the LOGO programming language in the chapter on LOGO. We also saw how to use the Python turtle module to do graphics programming in Python Turtle Graphics Basic chapter.

How about we write some programs that use both LOGO and Python turtle commands? Let’s write a program to make the turtle draw a Cartesian coordinates graph paper using LOGO and Python.

PROGRAM EXAMPLE: PYTHON TURTLE MODULE and LOGO TO DRAW A GRAPH PAPER

Program Name: turtle_draw_graph_paper.py

1  ###### File: turtle_draw_graph_paper.py ######
2  # This program draws Carteian Coordinates Graph Paper
3  
4  import turtle
5  
6  #3333 Set-up screen 333333
7  screen = turtle.Screen()
8  turtle.setup(800,800)
9  screen.title("Draw a Cartesion Coordinates Graph Paper")
10  screen.bgcolor("white")
11  
12  ###### Set-up Turtle object properties ######
13  TRTL = turtle.Turtle() # TRTL is turtle object.
14  TRTL.color("black")
15  TRTL.shape("classic")
16  
17  #####  DEFINE FUNTIONS ######
18  # This finction draws a line from point (x1, y1) to point (x2, y2)
19  def drawLine (TRTL, x1, y1, x2, y2):
20    TRTL.penup()
21    TRTL.goto (x1, y1)
22    TRTL.pendown()
23    TRTL.goto (x2, y2)
24    TRTL.penup()
25  
26  # Write label at location (x, y)
27  # This function writes coordinates on x-axis and y-axis.
28  def labelLocation (TRTL, x, y, label):
29    TRTL.penup()
30    TRTL.goto (x, y)
31    TRTL.pendown()
32    TRTL.write (label)
33    TRTL.penup()
34  
35  # This function marks a line on x-axis and y-axis.
36  def drawMarkOnAxis (TRTL, x, y):
37    drawLine (TRTL, x, y + 7, x, y - 7)
38    drawLine (TRTL, x - 7, y, x + 7, y)
39  
40  # This function calls function "labelLocation" to write label on x-axis and y-axis.
41  def coordinateLocation (TRTL, x, y, text):
42    labelLocation (TRTL, x - 30, y - 20, text)
43  
44  ###### END OF FUNCTION DEFINITIONS ######
45    
46  ###### MAIN PROGRAM ######
47  # Draw x-axis and y-axis
48  TRTL.pensize(2)
49  TRTL.pencolor("blue")
50  drawLine (TRTL, -400, 0, 400, 0)
51  drawLine (TRTL, 0, 400, 0, -400)
52  
53  # Put marks and write labels x-axis.
54  TRTL.pencolor("black")
55  for x in [-300, -200, -100, 0, 100, 200, 300]:
56    drawMarkOnAxis (TRTL, x, 0)
57    coordinateLocation (TRTL, x, 0, (int(x/100), 0))
58  
59  # Put marks and write labels y-axis.
60  for y in [-300, -200, -100, 100, 200, 300]:
61    drawMarkOnAxis (TRTL, 0, y)
62    coordinateLocation (TRTL, 0, y, (0, int(y/100)))
63  
64  # Draw Vertical lines on the graph paper.
65  TRTL.pensize(1)
66  for i in (-300, -200, -100, 100, 200, 300):
67    drawLine(TRTL, i, -300, i, 300)
68  
69  # Draw horixontal lines on the graph paper.
70  for i in (-300, -200, -100, 100, 200, 300):
71    drawLine(TRTL, -300, i, 300, i)
72  
73  # Draw graph paper border.
74  TRTL.pensize(3)
75  TRTL.pencolor("red")
76  drawLine(TRTL, -350, -350, 350, -350)
77  TRTL.left(90)
78  drawLine(TRTL, 350, -350, 350, 350)
79  TRTL.left(90)
80  drawLine(TRTL, 350, 350, -350, 350)
81  TRTL.left(90)
82  drawLine(TRTL, -350, 350, -350, -350)
83  ###### END OF MAIN PROGRAM ######

Copy this program and run it on your computer to see the output. Below is the program output.

turtle_draw_graph_paper.py Program Output

Turtle Graphics Use Python and LOGO in the Same Program
Turtle Graphics: Python and LOGO in the Same Program

Copyright © 2019 – 2021 softwareprogramming4kids.com

All Rights Reserved

Verified by MonsterInsights