0% found this document useful (0 votes)
22 views

Turtle World

The document discusses turtle graphics in Python. Turtle graphics allows programmers to direct the movement of an on-screen turtle using methods like forward(), left(), etc. The turtle can draw lines as it moves. The document covers turtle concepts like positioning, headings, colors, drawing shapes and circles.

Uploaded by

anujking959
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Turtle World

The document discusses turtle graphics in Python. Turtle graphics allows programmers to direct the movement of an on-screen turtle using methods like forward(), left(), etc. The turtle can draw lines as it moves. The document covers turtle concepts like positioning, headings, colors, drawing shapes and circles.

Uploaded by

anujking959
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Introduction to Programming in Python

Turtle Graphics

Dr. Bill Young


Department of Computer Science
University of Texas at Austin

Last updated: June 4, 2021 at 11:44

Texas Summer Discovery Slideset 15: 1 Turtle Graphics


Turtle Graphics

Turtle graphics was first developed as part of the children’s


programming language Logo in the late 1960’s. It exemplifies OOP
extremely well. You will be using classes already defined for you.

Texas Summer Discovery Slideset 15: 2 Turtle Graphics


Turtle Graphics

Turtles are just Python objects, so you can use


any Python constructs in turtle programs:
selection, loops, recursion, etc.
Turtles are objects that move about on a
screen (window).
Various methods allow you to direct the
turtle’s movement.
The turtle’s tail can be up or down. When it is
down, the turtle draws on the screen as it
moves.
You can draw some pretty awesome images!

Texas Summer Discovery Slideset 15: 3 Turtle Graphics


A Turtle Drawing

Texas Summer Discovery Slideset 15: 4 Turtle Graphics


A Turtle Drawing

Texas Summer Discovery Slideset 15: 5 Turtle Graphics


A Turtle Drawing: I Drew This One

A version of this picture was published in: William D. Young.


“Modeling and Verification of a Simple Real-Time Gate
Controller,” in Michael Hinchey and Jonathan Bowen, editors,
Applications of Formal Methods, Prentice-Hall Series in Computer
Science, 1995, pp. 181–202.
Texas Summer Discovery Slideset 15: 6 Turtle Graphics
The Turtle’s Data

Like all Python classes, the turtle class defines data and methods.
The data (state) of the turtle consists of:
Position: denoted by its current x and y coordinates; the units
are pixels.
Heading: denoted by an angle in degrees. East is 0 degrees.
north is 90 degrees; west is 180 degrees; south is 270
degrees.
Color: the color can be set to 224 (∼ 16.8 million) colors.
Width: the width of the line drawn as the turtle moves
(initially 2 pixels).
Down: a Boolean attribute indicating whether the turtle’s
tail is down.

Texas Summer Discovery Slideset 15: 7 Turtle Graphics


Coordinate Grid

Texas Summer Discovery Slideset 15: 8 Turtle Graphics


Turtle Methods

Many turtle methods are listing in your textbook (pages 81, 83)
and online; Google “python turtle graphics.”
t = Turtle() create a new Turtle object and open its window
t.home() move the turtle to (0, 0), pointing east
t.pendown() lower the tail (t.down() also works)
t.penup() raise the tail (t.up() also works)
t.pensize(k) set linewidth to k pixels
t.setheading(d) change heading to direction d
t.left(d) turn left d degrees
t.right(d) turn right d degrees
t.speed(n) how fast the turtle moves (0 .. 10)
t.setx(n) set the turtle’s x coordinate, leave y unchanged
t.sety(n) set the turtle’s y coordinate, leave x unchanged

Texas Summer Discovery Slideset 15: 9 Turtle Graphics


Turtle Methods

t.forward(n) move in the current direction n pixels


t.backward(n) move in the reverse direction n pixels
t.goto(x, y) move to coordinates (x , y )
t.position() return the current position at a tuple (x, y)
t.heading() return the current direction (angle)
t.isdown() return True if the pen is down
t.pencolor(r, g, b) change the color to the specified RGB value or
named color
t.write(s, font) write a message to the screen (you can specify font
and size, e.g., “font=(’Arial’, 8, normal)”

Texas Summer Discovery Slideset 15: 10 Turtle Graphics


Keeping it On Screen

Because the window goes away immediately after the program


terminates, it may be hard to see the result unless you delay
things. You can use t.done() for that.
t.done() make the screen persist until you close it

The turtle itself will appear on your screen as a small arrowhead.


You can decide whether to show or hide the turtle.
t.hideturtle() make the turtle invisible
t.showturtle() make the turtle visible
t.isvisible() return True if the turtle is visible

Texas Summer Discovery Slideset 15: 11 Turtle Graphics


A Turtle Function: Draw Square

import turtle
def drawSquare ( ttl , x , y , length ) :
""" Draws a square using turtle ttl , with upper left
corner at (x , y ) , and side of length """
ttl . penup () # raise the pen
ttl . goto (x , y ) # move to starting position
ttl . setheading (0) # point turtle east
ttl . pendown () # lower the pen
for count in range (4) : # draw 4 sides :
ttl . forward ( length ) # move forward length ;
ttl . right (90) # turn right 90 degrees
ttl . penup () # raise the pen

Bob = turtle . Turtle () # our turtle is named Bob


Bob . speed (10) # make Bob crawl fast
Bob . pensize (3) # line width of 3 pixels
drawSquare ( Bob , 0 , 0 , 100 ) # draw a square at (0 ,0)
# with side length 100
turtle . done () # keep drawing showing

Texas Summer Discovery Slideset 15: 12 Turtle Graphics


What the Turtle Drew

Texas Summer Discovery Slideset 15: 13 Turtle Graphics


Colors
I’m not sure this works on all versions of turtle graphics.
Colors are in the RGB system, using a triple: (R, G, B). Each
element in the triple is an intensity from 0 to 255, indicating the
contribution of R (red), G (green), and B (blue). For example:
black (0,0,0)
red (255,0, 0)
green (0, 255, 0)
blue (0, 0, 255)
gray (127, 127, 127)
white (255, 255, 255)
burnt orange (255, 125, 25)
This is a nice website that allows you to find the RGB values for
various colors: www.colorschemer.com/color-picker.
The named Python colors can be found here:
https://python-graph-gallery.com/python-colors/.
Texas Summer Discovery Slideset 15: 14 Turtle Graphics
Color Wheel

Texas Summer Discovery Slideset 15: 15 Turtle Graphics


Colors
Turtles have two “colormodes” and you’ll get an error if you try to
do some things in the wrong mode. The modes are 1.0 and 255.
In mode 255, use triples of range 0 ≤ c ≤ 255. In mode 1, use
triples (percentages) in range 0 . . . 1.
>>> t = Turtle ()
>>> t . pencolor (127 , 127 , 127)
Traceback ( most recent call last ) :
File " < stdin > " , line 1 , in < module >
....
raise T u r t l e G r a p h i c s E r r o r ( " bad color sequence : % s " % str
( color ) )
turtle . T u r t l e G r a p h i c s E r r o r : bad color sequence : (127 , 127 ,
127)

>>> t . pencolor (0.5 , 0.5 , 0.5)


>>> t . screen . colormode (255)
>>> print ( t . screen . colormode () )
255
>>> t . pencolor (127 , 127 , 127)
>>> t . screen . colormode (1)

Texas Summer Discovery Slideset 15: 16 Turtle Graphics


Another Way

If you’re in colormode 255, you can also specify the color with a
hex string value.
For example, the color Burnt Orange can be specified with the
RGB decimal triple: (255, 125, 25).
You can also specify it with the hex string value: ’#FF7D19’
because 255 is hex (base 16) value FF, 125 is hex value 7D, and 25
is hex value 19.

>>> ttl . screen . colormode (255)


>>> ttl . pencolor (255 , 125 , 25)
>>> print ( ttl . pencolor () )
(255.0 , 125.0 , 25.0)
>>> ttl . pencolor ( ’# FF7D19 ’)
>>> print ( ttl . pencolor () )
(255.0 , 125.0 , 25.0)

Texas Summer Discovery Slideset 15: 17 Turtle Graphics


Circles
You can draw circles, arcs, and dots using these functions:

t.circle(r, ext, step) draw a circle with radius r, ext (arc of circle
drawn; 360 is entire circle), step (number of
segments).
t.dot(d, color) draw a filled circle with diameter r and color

Note: the circle is not centered at the starting point. If you want
that you could write:
def centered Circle ( ttl , r , x , y ) :
""" Draw a circle with radius r centered at (x , y ) . """
ttl . up () # raise the pen
angle = ttl . heading () # save the current heading
ttl . setheading (0) # set heading east
ttl . goto (x , y - r ) # move to bottom of circle
ttl . down () # pen down
ttl . circle ( r ) # draw the circle
ttl . up () # pen up
ttl . setheading ( angle ) # restore the heading

Texas Summer Discovery Slideset 15: 18 Turtle Graphics


Circles

def d ra wS om e Ci rc le s ( ttl ) :
ttl . speed (10)
ttl . pensize (3) # line is 3 pixels
ttl . up ()
ttl . home () # go to (0 , 0)
ttl . down ()
ttl . pencolor ( ’ Green ’)
ttl . circle (25) # rad . 25 pixels
ttl . up ()
ttl . goto (0 , 0)
ttl . pencolor ( ’ Red ’)
ttl . down ()
ttl . circle (50 ,180) # arc 180 deg .
ttl . up ()
ttl . goto (0 , 0)
ttl . pencolor ( ’ Blue ’)
ttl . down ()
ttl . circle (75 ,360 ,8) # octogon
ttl . up ()

Sam = turtle . Turtle ()


d ra wS om eC i rc le s ( Sam )

Texas Summer Discovery Slideset 15: 19 Turtle Graphics


More with Circles

def tangentC ircles ( ttl ) :


""" Print 10 tangent circles . """
r = 10 # initial radius
n = 10 # count of circles
for i in range (1 , n + 1 , 1) :
ttl . circle ( r * i )

def c o n c e n t r i c C i r c l e s ( ttl ) :
""" Print 10 concentric circles . """
r = 10 # initial radius
for i in range (10) :
ttl . circle ( r * i )
ttl . up ()
ttl . sety (( r * i ) *( -1) )
ttl . down ()

Ben = turtle . Turtle ()


Ben . up () ; Ben . goto (0 , 150)
Ben . down () ; Ben . pencolor ( ’ Blue ’)
tange ntCircle s ( Ben )
Ben . up () ; Ben . goto (0 , -150)
Ben . down () ; Ben . pencolor ( ’ Red ’)
c o n c e n t r i c C i r c l e s ( Ben )
Texas Summer Discovery Slideset 15: 20 Turtle Graphics
Fill Areas

If you draw a closed region, you can fill it with a specified color:
t.fillcolor() sets the pen fill color
t.begin fill() call this before filling a shape
t.end fill() call to no longer keep filling
t.filling() return True if filling, False otherwise

Texas Summer Discovery Slideset 15: 21 Turtle Graphics


Drawing a Chessboard
def m ay be Fi l lS qu ar e ( ttl , x , y , lngth , fill , color ) :
""" Boolean parameter fill says whether to fill . """
if fill :
ttl . fillcolor ( color )
ttl . begin_fill ()
drawSquare ( ttl , x , y , lngth )
ttl . end_fill ()
else :
drawSquare ( ttl , x , y , lngth )

def drawChes sboard ( ttl , x , y , squaresize ) :


""" Draw a teal and white chessboard . """
fill = True
for j in range ( 8 ) :
for i in range ( 8 ) :
x1 = x + i * squaresize
y1 = y - j * squaresize
m ay be Fi l lS qu ar e ( ttl , x1 , y1 , squaresize ,
fill , ’ teal ’)
fill = not fill
fill = not fill

Matt = turtle . Turtle ()


drawC hessboar d ( Matt , 0 , 0 , 20 )
Texas Summer Discovery Slideset 15: 22 Turtle Graphics
Our Chessboard

I don’t know why those weird lines are in there. They don’t show
up on the screen.

Texas Summer Discovery Slideset 15: 23 Turtle Graphics


Sierpinski Curve

Texas Summer Discovery Slideset 15: 24 Turtle Graphics


Some Complex Stuff: Sierpinski Curve

def oneSide ( ttl , s , diag , level ) :


if ( level == 0) :
return
else :
oneSide ( ttl , s , diag , level - 1 )
ttl . right (45) ; ttl . forward ( diag ) ; ttl . right (45)
oneSide ( ttl , s , diag , level - 1 )
ttl . left (90) ; ttl . forward ( s ) ; ttl . left (90)
oneSide ( ttl , s , diag , level - 1 )
ttl . right (45) ; ttl . forward ( diag ) ; ttl . right (45)
oneSide ( ttl , s , diag , level - 1 )

def sierpinski ( ttl , s , level ) :


diag = s / math . sqrt (2)
for i in range (4) :
oneSide ( ttl , s , diag , level )
ttl . right (45)
ttl . forward ( diag )
ttl . right (45)

Texas Summer Discovery Slideset 15: 25 Turtle Graphics


Some Complex Stuff: Fractal Triangles

Texas Summer Discovery Slideset 15: 26 Turtle Graphics


Fractal Triangles

def d r a w O u t w a r d T r i a n g l e s ( ttl , size ) :


if size < 10:
return
for i in range ( 3 ) :
ttl . forward ( size / 2 )
insert ( ttl , size )
ttl . forward ( size / 2 )
ttl . right ( 120 )

def insert ( ttl , size ) :


ttl . left ( 120 )
d r a w O u t w a r d T r i a n g l e s ( ttl , size / 2 )
ttl . right ( 120 )

Ken = turtle . Turtle ()


Ken . color ( " blue " )
d r a w O u t w a r d T r i a n g l e s ( Ken , 200 )

Texas Summer Discovery Slideset 15: 27 Turtle Graphics


Saving Your Picture
Python saves your picture as a postscript file, but you can convert
it. To save your picture as a jpeg, do the following:
from PIL import Image

def save_as_jpg ( canvas , fileName ) :


# save postscipt image
canvas . postscript ( file = fileName + ’. eps ’)
# use PIL to convert to JPEG
img = Image . open ( fileName + ’. eps ’)
img . save ( fileName + ’. jpeg ’ , ’ jpeg ’)

< Your drawing functions >

ts = turtle . getscreen ()
tc = ts . getcanvas ()
# creates a postscript image file
# substitute your own filename
tc . postscript ( file = " filename . eps " )
# converts to JPEG
save_as_jpg ( tc , " filename " )

turtle . done ()

Texas Summer Discovery Slideset 15: 28 Turtle Graphics


Seychelles Flag

Texas Summer Discovery Slideset 15: 29 Turtle Graphics


Drawing the Seychelles Flag

# This draws the flag of the Seychelles islands :

import turtle
from PIL import Image

def save_as_jpg ( canvas , fileName ) :


# same as before
...

def drawRectangle ( ttl , x , y , width , height ) :


""" Draw a rectangle of dimensions width and
height , with upper left corner at (x , y ) . """
ttl . up ()
ttl . goto (x , y )
ttl . setheading (0)
ttl . down ()
for i in range (2) :
ttl . forward ( width )
ttl . right (90)
ttl . forward ( height )
ttl . right (90)
ttl . up ()

Texas Summer Discovery Slideset 15: 30 Turtle Graphics


Drawing the Seychelles Flag

def drawTriangle ( ttl , x1 , y1 , x2 , y2 , x3 , y3 ) :


ttl . penup ()
ttl . goto ( x1 , y1 )
ttl . pendown ()
ttl . goto ( x2 , y2 )
ttl . goto ( x3 , y3 )
ttl . goto ( x1 , y1 )
ttl . penup ()

def fillTriangle ( ttl , x1 , y1 , x2 , y2 , x3 , y3 , color ) :


# This assumes color is given as a Hex string value .
ttl . fillcolor ( color )
ttl . begin_fill ()
drawTriangle ( ttl , x1 , y1 , x2 , y2 , x3 , y3 )
ttl . end_fill ()

Texas Summer Discovery Slideset 15: 31 Turtle Graphics


Drawing the Seychelles Flag
# set up the screen size ( in pixels - 1000 x 1000)
# set the starting point of the turtle (0 , 0)
turtle . setup (1500 , 1000 , 0 , 0)
myBlue = ’ #003882 ’
myYellow = ’# FCD647 ’
myRed = ’# D12421 ’
myGreen = ’ #007336 ’
myWhite = ’# FFFFFF ’
Joe = turtle . Turtle ()
Joe . screen . colormode (255)
drawRectangle ( Joe , 0 , 300 , 600 , 300 )
Joe . goto (0 , 0)

# draw blue triangle


fillTriangle ( Joe , 0 , 0 , 0 , 300 , 200 , 300 , myBlue )
# draw yellow triangle
fillTriangle ( Joe , 0 , 0 , 200 , 300 , 400 , 300 , myYellow )
# draw red triangle
fillTriangle ( Joe , 0 , 0 , 400 , 300 , 600 , 300 , myRed )
# draw white triangle
fillTriangle ( Joe , 0 , 0 , 600 , 300 , 600 , 150 , myWhite )
# draw green triangle
fillTriangle ( Joe , 0 , 0 , 600 , 150 , 600 , 0 , myGreen )

Texas Summer Discovery Slideset 15: 32 Turtle Graphics


Drawing the Seychelles Flag

Joe . hideturtle ()

ts = turtle . getscreen ()
tc = ts . getcanvas ()
# creates a postscript image file
# substitute your own filename
tc . postscript ( file = " S eychelle sFlag . eps " )
# converts to JPEG
save_as_jpg ( tc , " Seyc hellesFl ag " )

turtle . done ()

Texas Summer Discovery Slideset 15: 33 Turtle Graphics


Some Sample Projects

Write Turtle graphics functions that will do the following:


1 draw a cube;
2 draw a regular polygon with k sides and radius r (distance
from center to one of the vertices);
3 draw m concentric circles, varying the color as you go outward;
4 draw the flag of some country;
5 draw a building.

Texas Summer Discovery Slideset 15: 34 Turtle Graphics

You might also like