/* jquery */ /* jquery accordion style*/ /* jquery init */

18 May 2013

Learn Python - Turtle Shapes

This time, rather than drawing patterns with lines we'll use shapes filled with colour, like this...

Let's get started. Open an new file in your editor and save it as 'turtle-shapes.py'.
Now type in the code below:

from turtle import *

# set a shape and colour
shape("circle")
shapesize(5,1,2)
fillcolor("red")
pencolor("darkred")

penup() # no drawing
goto(0, -100)

# main draw loop
for i in range(72):
  forward(10)
  left(5)
  tilt(7.5)
  stamp()

exitonclick()

The first thing this program does is define the turtle shape with the shape function call. Here we are going to use a circle, but it could also be a triangle or a square.

On the next line we have a shapesize function call with three parameters. These specify the shape length, width and outline thickness respectively. Here the parameter values 5,1,2 will stretch our circle to create a thin ellipse.

We fill the ellipse shape with colour using the fill function. Here we've set it to red. We've also set the pen colour, to provide a contrasting shape outline colour. So, now our turtle is solid red ellipse with a dark red outline.

The next line issues a penup command. This raises the turtle's pen and stops it from drawing a line as it moves. It will become clear why we do this shortly.

By default our turtle is positioned at the centre of the window. However, for this program we need to move it a little first, to create room for our pattern. Although we could use the standard turn and movement commands, this time we'll use the goto function call because it can be done in a single command.

The goto command instructs the turtle to move to a new position relative to its current location. The move is specified as X and Y axis movements. The first X parameter is zero, so we won't move left or right. But, the Y value is -100. This moves the turtle down the screen by 100 steps.

Now we have the main draw loop, which repeats 72 times. Each time it will move forward 10 steps, turn left 5 degrees, tilt our ellipse shape by 7.5 degrees and do a stamp. What does stamp do? Stamp will leave an impression of our turtle, namely our red ellipse, on the screen.

Save the code and run the program, to see the stamped red ellipses gradually build up a pattern. Yet there's loads of ways to modify this program.

Try different values for forward, left and tilt in the loop and discover what sort of patterns are generated. You might be surprised at the results.

The shape of the ellipse can be altered by using different parameter values in the shapesize function call. And, of course, you're free to use any colour, or colours, you like.

A post from my Learn Python on the Raspberry Pi tutorial.