May5

ComputerScienceFundamentals107
VisualizingRecursion
UsingthePythonTurtle
DrawingFractals
ThePythonTurtle
Turtleisapythonfeature,likeadrawingboardwhich
letsyoucommandaturtletodrawalloverit!
2
ExamplesofTurtleOpera>ons
E.g.aturtlestarFngsomewhereinthex-yplaneand
iniFallyfaceseast.Giveitthecommand
turtle.forward(15),anditmoves(on-screen!)15pixels
inthedirecFonitisfacing,drawingalineasitmoves.
Giveitthecommandturtle.right(25),anditrotatesinplace25degreesclockwise.
Theturtlealsohasthepenup/pendownfuncFonality
soitcanmovewithoutdrawing.
3
ThePythonTurtle
4
TheturtlemoduleisstandardwithallversionsofPython.
importturtle #importtheturtlemodule
defmain():
my_win=turtle.Screen()
tess=turtle.Turtle() …
tess.forward(50)
…
my_win.exitonclick()
main()
#createandopenawindow
#createaturtleobject
#usetheturtleobjecttodraw
#exitallwhentheuserclicksonthecanvas
IniFallytheturtleisplacedat
thecentreofthewindow(0,0)
andisfacingtotheright.
File:00Turtle.py
tess.shape('turtle')
TurtleMethodsandAAributes
forward(distance)–movetheturtleforward
backward(distance)–movetheturtlebackwards
right(angle)–turntheturtleclockwise
le[(angle)–turntheturtleanF-clockwise
up()–putstheturtletailup,i.e.,nodrawing
down()–putstheturtletaildown,i.e.,drawing
color(colour_name)–changesthecolouroftheturtle'stail
fillcolor(colour_name)–changesthecolourusedtofillapolygon
posiFon()–returnstheposiFonoftheturtle
goto(x,y)–movestheturtletoposiFonx,y
begin_fill()–remembersthestarFngpointforafilledpolygon
end_fill()–closesthepolygonandfillsitwiththecurrentfillcolor
shape('turtle')–settheshapetobeaturtleshape
stamp()–stampcopyoftheturtleshape
…andothers!
Documentation at
https://docs.python.org/2/library/turtle.html
5
TheTurtleobject-Example
File:01TurtleSnippets.py
6
TheTurtleobject-Example
importturtle
defdraw_spiral(luca,line_len):
ifline_len>0:
luca.forward(line_len)
luca.right(90)
draw_spiral(luca,line_len-5)
defmain():
my_win=turtle.Screen()
a_turtle=turtle.Turtle()
draw_spiral(a_turtle,100)
my_win.exitonclick()
main() File: 02TurtleSpiral.py
7
Fractals
Aself-similarpacerni.e.apacernthatrepeats
itselfateveryscale(asyouzoominorout).
Somefractalscanbedrawnusing
theTurtleobject.
hcps://en.wikipedia.org/wiki/Self-similarity(AnimaFon)
8
RecursiveDrawing-UsingtheTurtle
DrawafractalwithN
recursionlevels(order).
Basecase:iftheorder
is0drawastraightline.
Recursivecase:drawastraight
line,replacepartwithanangled
linesegments(forminga“bump”).
Callthisdrawingmethod
recursivelywithorder(n-1)for
eachlinesegmentoftheshape.
9
0
1
2
3
4
RecursiveDrawing-KochCurve
Westartoffwithasingleline
segment,thendivideitinto3
equalsegments.
Wedrawanequilateraltriangle
thathasthemiddlesegmentas
thebase.Wethenremovethe
middlesegment.
10
0
1
Weapplythis
procedurerecursively
onalllinesegments.
File: 03TurtleKochCurve.py
2
…
3
Similar:KochSnowflake
WatchWikipediaanimaFonat
hcps://en.wikipedia.org/wiki/Koch_snowflake
11
RecursiveDrawing-KochCurve
defdrawKoch(turtle,level,length):
iflevel==0:
turtle.forward(length)
else:
drawKoch(turtle,level-1,length/3)
turtle.leY(60)
drawKoch(turtle,level-1,length/3)
turtle.right(120)
drawKoch(turtle,level-1,length/3)
turtle.leY(60)
drawKoch(turtle,level-1,length/3)
12
RecursiveTree
RecursivedefiniFonofatree:
Atreeisatrunkwithasmaller
treebranchingofftotheright
andanothersmallertree
branchingofftotheright.
04TurtleTree.py
13
RecursiveDrawing–Sierpinski
DrawatrianglestarFngatbocom
le[corner,
Movetothebocomright
cornerandrepeat,
Movetotopcornerofle[triangle
andrepeat.
14
RecursiveSierpinski
05TurtleSierpinski.py
15