EMT1111

Turtle graphics

Using the turtle and random modules from Python, write a program (or script) to create an output screen as the one shown in the figure below.

To achieve this output you have to do the following:

  • Change the color of the window to ā€œredā€ using wn.bgcolor property of the screen variable you create.
  • Your turtle variable has to have a pen color ā€œwhiteā€, you have to use the .pencolor property of your turtle variable.
  • You have to make your turtle to change its heading to the right with an random angle between 0 and 45 degrees.
  • Move your turtle forward a random distance between 0 and 150 pixels.
  • Then move the turtle backward the same distance than above
  • Repeat the last three steps 100 times

In order to perform this exercise, we need first to import the modules Turtle and Random as follows:

>>import turtle

>>import random

Then we assign their names

t = turtle.Turtle()
r = random.Random()

After that we create the window (canvas)Ā and we make the color of the window “Red” using .bgcolorĀ and the color of the pen is “white” for the variable turtle.

>>window = turtle.Screen()
>>window.bgcolor(‘red’)
>>t.pencolor(‘white’)
We make the turtle to change its heading to the right with an random angle between 0 and 45 degrees and move forward and backward atĀ a random distance between 0 and 150 pixels. Then we repeat it for a hundred times.
>>for x in range(100):
angle = random.randint(0, 45)
t.right(angle)
distance = random.randint(0, 150)
t.forward(distance)
t.backward(distance)

Therefore, the final code for this exercise will look like :

And will be displayed as :