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

Turtle Element in Py

Turtle graphics was first developed in the 1960s as part of the Logo programming language. It exemplifies object-oriented programming by using predefined turtle classes. Turtles are Python objects that can move around on a screen using various methods, and their tail can be down to draw lines as they move. This allows users to draw complex images.

Uploaded by

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

Turtle Element in Py

Turtle graphics was first developed in the 1960s as part of the Logo programming language. It exemplifies object-oriented programming by using predefined turtle classes. Turtles are Python objects that can move around on a screen using various methods, and their tail can be down to draw lines as they move. This allows users to draw complex images.

Uploaded by

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

Turtle Graphics

CS303E: Elements of Computers


and Programming
Turtle Graphics

Dr. Bill Young


Department of Computer Science
University of Texas at Austin

Last updated: October 26, 2022 at 14:12 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.

CS303E Slideset 13: 1 Turtle Graphics CS303E Slideset 13: 2 Turtle Graphics

Turtle Graphics A Turtle Drawing

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!

CS303E Slideset 13: 3 Turtle Graphics CS303E Slideset 13: 4 Turtle Graphics
A Turtle Drawing 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.
CS303E Slideset 13: 5 Turtle Graphics CS303E Slideset 13: 6 Turtle Graphics

Coordinate Grid The Turtle’s Data

Like all Python classes, the turtle class defines data and methods.
The data (attributes) 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.

CS303E Slideset 13: 7 Turtle Graphics CS303E Slideset 13: 8 Turtle Graphics
Turtle Methods Turtle Methods

Many turtle methods are listing in your textbook (pages 81, 83)
and online; Google “python turtle graphics.”
t.forward(n) move in the current direction n pixels
t = Turtle() create a new Turtle object and open its window
t.backward(n) move in the reverse direction n pixels
t.home() move the turtle to (0, 0), pointing east
t.goto(x, y) move to coordinates (x , y )
t.pendown() lower the tail (t.down() also works)
t.position() return the current position at a tuple (x, y)
t.penup() raise the tail (t.up() also works)
t.heading() return the current direction (angle)
t.pensize(k) set linewidth to k pixels
t.isdown() return True if the pen is down
t.setheading(d) change heading to direction d
t.pencolor(r, g, b) change the color to the specified RGB value or
t.left(d) turn left d degrees
named color
t.right(d) turn right d degrees
t.write(s, font) write a message to the screen (you can specify font
t.speed(n) set how fast the turtle moves (0 .. 10) and size, e.g., “font=(’Arial’, 8, normal)”
t.setx(n) set the turtle’s x coordinate, leave y unchanged
t.sety(n) set the turtle’s y coordinate, leave x unchanged

CS303E Slideset 13: 9 Turtle Graphics CS303E Slideset 13: 10 Turtle Graphics

Keeping it On Screen A Turtle Function: Draw Square

Because the window goes away immediately after the program import turtle
terminates, it may be hard to see the result unless you delay def drawSquare ( ttl , x , y , length ) :
""" Draws a square using turtle ttl , with upper left
things. You can use turtle.done() for that. Note that this is a corner at (x , y ) , and side of length """
class method rather than an instance method; that means that you ttl . penup () # raise the pen
ttl . goto (x , y ) # move to starting position
need to use the class name turtle.done(), not the instance ttl . setheading (0) # point turtle east
leonardo.done(). ttl . pendown () # lower the pen
for count in range (4) : # draw 4 sides :
turtle.done() make the screen persist until you close it ttl . forward ( length ) # move forward length ;
ttl . right (90) # turn right 90 degrees
ttl . penup () # raise the pen
The turtle itself will appear on your screen as a small arrowhead.
You can decide whether to show or hide the turtle. Bob = turtle . Turtle () # our turtle is named Bob
Bob . speed (10) # make Bob crawl fast
t.hideturtle() make the turtle invisible Bob . pensize (3)
drawSquare ( Bob , 0 , 0 , 100 )
#
#
line width of 3 pixels
draw a square at (0 ,0)
t.showturtle() make the turtle visible # with side length 100
turtle . done () # keep drawing showing
t.isvisible() return True if the turtle is visible # note , it ’s a class method

CS303E Slideset 13: 11 Turtle Graphics CS303E Slideset 13: 12 Turtle Graphics
What the Turtle Drew Draw Some Triangles

import turtle

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 ()

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


Tom . speed (10) # make Tom crawl fast
Tom . pensize (3) # line width of 3 pixels

Tom . pencolor (1 , 0 , 0) # set pen to red


drawTriangle ( Tom , 0 , 0 , 50 , 100 , 100 , 0 )
Tom . pencolor (0 , 1 , 0) # set pen to green
drawTriangle ( Tom , 0 , 0 , 50 , -100 , 100 , 0 )
Tom . hideturtle ()

CS303E Slideset 13: 13 Turtle Graphics CS303E Slideset 13: 14 Turtle Graphics

What the Turtle Drew Let’s Take a Break

CS303E Slideset 13: 15 Turtle Graphics CS303E Slideset 13: 16 Turtle Graphics
Colors Color Wheel
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/.
CS303E Slideset 13: 17 Turtle Graphics CS303E Slideset 13: 18 Turtle Graphics

Colors Circles
Turtles have two “colormodes” and you’ll get an error if you try to You can draw circles, arcs, and dots using these functions:
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 t.circle(r, ext, step) draw a circle with radius r, ext (arc of circle
triples (percentages) in range 0 . . . 1. drawn; 360 is entire circle), step (number of
segments).
>>> t = Turtle ()
>>> t . pencolor (127 , 127 , 127) t.dot(d, color) draw a filled circle with diameter r and color
Traceback ( most recent call last ) :
File " < stdin > " , line 1 , in < module >
....
Note: the circle is not centered at the starting point. If you want
raise T u r t le G r a p h i c sE r r o r ( " bad color sequence : % s " % str that you could write:
( color ) )
turtle . T u r t l e G ra p h i c s E r r o r : bad color sequence : (127 , 127 , def centered Circle ( ttl , r , x , y ) :
127) """ Draw a circle with radius r centered at (x , y ) . """
ttl . up () # raise the pen
>>> t . pencolor (0.5 , 0.5 , 0.5) angle = ttl . heading () # save the current heading
>>> t . screen . colormode (255) ttl . setheading (0) # set heading east
>>> print ( t . screen . colormode () ) ttl . goto (x , y - r ) # move to bottom of circle
255 ttl . down () # pen down
>>> t . pencolor (127 , 127 , 127) ttl . circle ( r ) # draw the circle
>>> t . screen . colormode (1) ttl . up () # pen up
ttl . setheading ( angle ) # restore the heading

CS303E Slideset 13: 19 Turtle Graphics CS303E Slideset 13: 20 Turtle Graphics
Circles More with Circles

def d ra wSomeCircles ( ttl ) :


ttl . speed (10) def tangentC ircles ( ttl ) :
ttl . pensize (3) # line is 3 pixels """ Print 10 tangent circles . """
ttl . up () r = 10 # initial radius
ttl . home () # go to (0 , 0) n = 10 # count of circles
ttl . down () for i in range (1 , n + 1 , 1) :
ttl . pencolor ( ’ Green ’) ttl . circle ( r * i )
ttl . circle (25) # rad . 25 pixels
ttl . up () def c on c e n t ri cC ir cle s ( ttl ) :
ttl . goto (0 , 0) """ Print 10 concentric circles . """
ttl . pencolor ( ’ Red ’) r = 10 # initial radius
ttl . down () for i in range (10) :
ttl . circle (50 ,180) # arc 180 deg . ttl . circle ( r * i )
ttl . up () ttl . up ()
ttl . goto (0 , 0) ttl . sety (( r * i ) *( -1) )
ttl . pencolor ( ’ Blue ’) ttl . down ()
ttl . down ()
ttl . circle (75 ,360 ,8) # octogon Ben = turtle . Turtle ()
ttl . up () Ben . up () ; Ben . goto (0 , 150)
Ben . down () ; Ben . pencolor ( ’ Blue ’)
Sam = turtle . Turtle () tange ntCircle s ( Ben )
d rawSomeCircles ( Sam ) Ben . up () ; Ben . goto (0 , -150)
Ben . down () ; Ben . pencolor ( ’ Red ’)
c o n c e n tr i c Ci rc l e s ( Ben )
CS303E Slideset 13: 21 Turtle Graphics CS303E Slideset 13: 22 Turtle Graphics

Fill Areas Drawing a Chessboard


def m ay be Fil lSquare ( ttl , x , y , lngth , fill , color ) :
If you draw a closed region, you can fill it with a specified color: """ Boolean parameter fill says whether to fill . """
if fill :
t.fillcolor() sets the pen fill color ttl . fillcolor ( color )
ttl . begin_fill ()
t.begin fill() call this before filling a shape drawSquare ( ttl , x , y , lngth )
t.end fill() call to no longer keep filling ttl . end_fill ()
else :
t.filling() return True if filling, False otherwise 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 beFi l lS qu ar e ( ttl , x1 , y1 , squaresize ,
fill , ’ teal ’)
fill = not fill
fill = not fill

Matt = turtle . Turtle ()


drawC hessboard ( Matt , 0 , 0 , 20 )
CS303E Slideset 13: 23 Turtle Graphics CS303E Slideset 13: 24 Turtle Graphics
Our Chessboard Sierpinski Curve

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

CS303E Slideset 13: 25 Turtle Graphics CS303E Slideset 13: 26 Turtle Graphics

Some Complex Stuff: Sierpinski Curve Some Complex Stuff: Fractal Triangles

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)

CS303E Slideset 13: 27 Turtle Graphics CS303E Slideset 13: 28 Turtle Graphics
Fractal Triangles 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:
def d r a w O u t w a r d T r i a n g l e s ( ttl , size ) :
from PIL import Image
if size < 10:
return
def save_as_jpg ( canvas , fileName ) :
for i in range ( 3 ) :
# save postscipt image
ttl . forward ( size / 2 )
canvas . postscript ( file = fileName + ’. eps ’)
insert ( ttl , size )
# use PIL to convert to JPEG
ttl . forward ( size / 2 )
img = Image . open ( fileName + ’. eps ’)
ttl . right ( 120 )
img . save ( fileName + ’. jpeg ’ , ’ jpeg ’)
def insert ( ttl , size ) :
< Your drawing functions >
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 )
ts = turtle . getscreen ()
ttl . right ( 120 )
tc = ts . getcanvas ()
# creates a postscript image file
Ken = turtle . Turtle ()
# substitute your own filename
Ken . color ( " blue " )
tc . postscript ( file = " filename . eps " )
d r a w O u t w a r d T r i a n g l e s ( Ken , 200 )
# converts to JPEG
save_as_jpg ( tc , " filename " )

turtle . done ()

CS303E Slideset 13: 29 Turtle Graphics CS303E Slideset 13: 30 Turtle Graphics

Some Sample Projects We’re Done!

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 an American flag;
5 draw the UT Tower.

CS303E Slideset 13: 31 Turtle Graphics CS303E Slideset 13: 32 Turtle Graphics

You might also like