Learning Goal: I’m working on a python question and need an explanation and answer to help me learn.Labs for Fun: Turtle GraphicsObjective: learn Turtle GraphicsPrerequisites: installation of Python3 and IDLE, knowledge of the basic Python commandsAdditional Resources:The Beginner’s Guide to Python Turtle – Real Python (Links to an external site.)

Turtle programming in Python (tutorialspoint.com) (Links to an external site.)

turtle — Turtle graphics — Python 3.8.8 documentation (Links to an external site.)

Turtle Race! – Introduction | Raspberry Pi Projects (Links to an external site.)

Data files in Files/Labs for Fun on Canvas

Topics: Turtle Graphics Overview

Turtle Graphics API

Basic Commands

Fractals and Recursion

Animation

Turtle Graphics OverviewTurtle Graphics is a 2D Graphics generated by an interactive tool named Turtle. Turtle is a program for drawing shapes and images and is named so because it emulates a moving turtle that also functions as a pen that draws lines as it moves. The turtle module in Python is located in the folder turtledemo and is a part of the standard library. So, you do not need to use pip and install any external libraries! Programming with Turtle is fun and very educational. Even though, using Turtle is considered by many an easy task (it is used for teaching programing to kids), I believe that programming with Turtle can be very challenging. Turtle can be used for generating complex and not complex fractals and is an ideal tool for learning recursions. Using Turtle can be tricky especially when you use it for recursions.Turtle APIThe main class of the turtle module is a Turtle. A turtle object has pen size, speed, shape, and color attributes:shapesize(1,1,1) # default values: length, width, outline width

pensize(1) # default value

shape(“turtle”) # can be triangle, circle, arrow, classic

fillcolor(“red”) # default fill is black

pencolor(“green”) # default outline is black

color(“green”, “red”) # sets both colors, fill and outline

speed(1) # default 0

Another main class is a Screen. A screen object has properties of a window and a canvas including title, background color, and window size. You can also control drawings by associating them with events. title()

bgcolor()

bgpic()

screensize()

clear()

Events and Animation Controldelay()

update()

listen()

onkey()

onkeypress()

onclick()

ontimer()

mainloop()

register_shape()

You can look at this site for additional information about Turtle Graphics API turtle — Turtle graphics — Python 3.8.8 documentation (Links to an external site.).Basic CommandsA Turtle object obeys the following basic commands:penup()pendown()right(angle) # parameter is an angle in degrees; shortcut rt() left(angle) # parameter is an angle in degrees; shortcut lt()forward(steps) # parameter is a distance; shortcut fd()backward(steps) # parameter is a distance; shortcut bk()goto(x, y) # parameters are Cartesian coordinateshome() # go to the origin (0, 0)undo() # undo the last stepclear() # clear the drawingThere are additional turtle commands that are described at this website: Turtle programming in Python (tutorialspoint.com) (Links to an external site.). The following example show the usage of basic turtle commands.Example 1. Making Basic Shapes## DRAW SHAPES#import turtle# draw a circledef draw_circle(t, size): t.pendown() t.begin_fill() t.circle(size) t.end_fill()# draw a triangledef draw_triangle(t, size): t.pendown() t.begin_fill() t.fd(size) t.lt(120) t.fd(size) t.lt(120) t.fd(size) t.end_fill()# draw a rectangledef draw_rectangle(t, width, height): t.pendown() t.begin_fill() for i in range(4): t.forward(width); t.left(90); t.end_fill() # draw a stardef draw_star(t, size): t.pendown() t.begin_fill() for i in range(5): t.forward(size); t.left(144); t.end_fill() # draw spiraldef draw_spiral(t, size, factor, angle): t.pendown() for x in range(size): t.fd(factor*x) t.left(angle)# main programs = turtle.Screen() # make a canvas windows.setup(400, 400)s.bgcolor(“ivory4”)s.title(“Turtle Program”)t = turtle.Turtle() # make a pent.shape(“turtle”) t.pen(pencolor=’dark violet’,fillcolor=’dark violet’, pensize=1, speed=0)t.penup() t.goto(-150,100) # move the pen to the left upper cornerdraw_circle(t, 20)t.penup() t.goto(100,-100) # move the pen to the right bottom cornert.color(‘gold’)draw_rectangle(t, 50, 70)t.penup() t.goto(-150,-100) # move the pen to the left bottom cornert.color(‘aqua’)draw_triangle(t, 50)t.penup()t.goto(120,150) # move the pen to the right upper cornert.color(‘red’)draw_star(t, 50)t.penup()t.home() # move the pen to the centert.color(‘coral’)draw_spiral(t, 80, 2, 92)t.penup()t.home() Fractals and RecursionFractals are geometrical patterns that have self-similarity, a special kind of symmetry of repeating itself at different scales. Fractals are not 2D or 3D figures – they have fractal dimensions, for example, the Sierpinski triangle, a fractal, has Hausdorff dimension of log(3)/log(2)≈1.58, whereas a regular triangle has Hausdorff dimension of 2 (as all other 2D shapes). Check the list of fractals and their dimensions here: List of fractals by Hausdorff dimension – Wikipedia (Links to an external site.). Fractals occur in nature: coastlines, mountains, plants, clouds, lightning bolts, snowflakes, rivers, and networks are examples of fractals. To visualize or create fractals by computer programs, we use recursions.Recursion is the process of executing the same procedure (a function) multiple times by calling the procedure from inside of the procedure itself. You can visualize recursion as reflection of a mirror in another mirror. In logic and mathematics, recursions are used as the foundation of induction, the most important mathematical proof method. Recursions are used to define various mathematical sets (Mandelbrot set) and functions (Fibonacci numbers). In computer science, recursions are used in dynamical programming (implementing AI for playing chess).Recursions could be infinite – to stop recursions we use restrictions such as how many times to execute recursions. All recursions are made of the base case(s) and recursive step. In programming, the base case(s) are used to stop the propagation of the recursive call. For example, let’s create a recursion of printing numbers from 1 to n. First, we need to find out what the base case is. Since we print numbers from 1 to n and our input is n, we deduce that the base case is printing 1. Then we add recursive step that is made of two statements recursion call and a print statement. If we want to print the numbers in the reverse order, we can simply exchange the statement print_numbers(n-1) with the statement print(n).# recursion tutorialdef print_numbers(n): if n == 1: print(n) else: print_numbers(n-1) # recursion call print(n)# main programprint_numbers(10)You can read more about recursions here: Recursion (computer science) – Wikipedia (Links to an external site.) We can use recursions and Turtle Graphics to visualize fractals. You can read the following codes to learn how to make fractals and implement recursions.Example 2. Tree Fractal# draws a treeimport turtle# set the canvas windowdef set_canvas(): s = turtle.Screen() s.setup(450, 410) s.bgcolor(‘ivory’) s.title(‘Turtle Program’) return s# set a turtle (a pen)def set_pen(color): t = turtle.Turtle() t.shape(‘turtle’) t.pen(pencolor=color,fillcolor=color, pensize=1, speed=10) return t# draw a tree fractal using recursiondef draw_tree(t, branch, angle, iteration): if iteration > 0: # recursive step t.color(‘brown’) t.pensize(iteration) t.forward(branch) length = branch * 9/10 t.left(angle) draw_tree(t, length, angle, iteration-1) # recursion call (left branch of the tree ‘branch’) t.color(‘brown’) t.right(angle * 2) t.pensize(iteration) t.forward(branch/10) draw_tree(t, length, angle, iteration-1) # recursion call (right branch of the tree ‘branch’) t.color(‘brown’) t.left(angle) t.backward(branch*11/10) else: # base case t.color(‘green’) t.pendown() t.dot(15)# main programs = set_canvas()t = set_pen(‘brown’)t.penup()t.goto(-45, -150)t.left(90)t.pendown()draw_tree(t, 60, 20, 6) Example 3. Sierpinski Triangle# draws Sierpinski triangleimport turtle# set canvasdef set_canvas(): s = turtle.Screen() s.setup(450, 450) turtle.bgcolor(“ivory”) turtle.title(“Sierpinski Triangle”) return s# set a turtle (a pen)def set_pen(color): t = turtle.Turtle() t.shape(“turtle”) t.pen(pencolor=color,fillcolor=color, pensize=1, speed=5) return t# draw a triangledef draw_triangle(vertices,color,my_turtle): my_turtle.fillcolor(color) my_turtle.up() my_turtle.goto(vertices[0][0],vertices[0][1]) my_turtle.down() my_turtle.begin_fill() my_turtle.goto(vertices[1][0],vertices[1][1]) my_turtle.goto(vertices[2][0],vertices[2][1]) my_turtle.goto(vertices[0][0],vertices[0][1]) my_turtle.end_fill() # find the midpointdef midpoint(point1, point2): return [(point1[0] + point2[0])/2, (point1[1] + point2[1])/2] # draw Sierpinski triangle recursivelydef draw_Sierpinski(vertices, level, my_turtle): global colors if level > 0: # recursive step draw_triangle(vertices,colors[level],my_turtle) # this is optional draw_Sierpinski([vertices[0], midpoint(vertices[0], vertices[1]), midpoint(vertices[0], vertices[2])], level – 1, my_turtle) draw_Sierpinski([vertices[1], midpoint(vertices[0], vertices[1]), midpoint(vertices[1], vertices[2])], level – 1, my_turtle) draw_Sierpinski([vertices[2], midpoint(vertices[2], vertices[1]), midpoint(vertices[0], vertices[2])], level – 1, my_turtle) else: # base case draw_triangle(vertices,colors[level],my_turtle)# main programs = set_canvas()t = set_pen(“black”)t.left(90)colors = [“red”,”gold”, “aqua”, “navy”, “cadet blue”]vertices = [[-200, -100], [0, 200], [200, -100]]draw_Sierpinski(vertices, 4, t) AnimationTurtle Graphics can be used to create simple games and animations. It is very easy to make animations when you use the turtle module in Python. You even do not have to implement anything additional for animation because when you create a turtle, the window, canvas, and animation loop are automatically generated for you. To learn how to use animation with the turtle module, you can look at the code and video of the popular game Turtle Race below.# turtle racefrom turtle import *from random import randintdef set_turtles(colors): turtles = [] for color in colors: t = Turtle() t.color(color) t.shape(“turtle”) t.speed(1) turtles.append(t) return turtlesdef draw_track(start, finish): t = Turtle() t.speed(0) position, size, step = 100, 200, 40 count = 0 for line in range(start, finish + step, step): t.penup() t.goto(line,position+10) if line == start: t.color(“blue”) t.pensize(10) t.write(“START”) elif line == finish: t.color(“red”) t.pensize(10) t.write(“FINISH”) else: t.color(“grey”) t.pensize(1) t.write(count) t.goto(line,position) count += 1 t.right(90) t.pendown() t.forward(size) t.left(90) def isfinish(t, finish): x, y = t.pos() if x < finish: return False else: return Truedef race(turtles, start, finish): # y position position = 80 distance = 40 for t in turtles: t.penup() t.left(180) t.goto(start, position) position -= distance t.left(180) t.pendown() done = False while not done: for t in turtles: t.forward(randint(1,10)) if isfinish(t, finish): done = True # main programs = Screen() # make a canvas windows.setup(500, 400)s.bgcolor(“white”)s.title(“Turtle Race”)start = -200 # x positionfinish = 200 # x positiondraw_track(start, finish)turtles = set_turtles([“yellow”, “crimson”, “aqua”, “green”, “purple”])race(turtles, start, finish) ExercisesIf you want to practice with Turtle Graphics, you can complete the following exercises. You can complete only one of them, it is up to you. You can get extra credit of 5 points per problem (the max credit is 25 points). Problem1. Write a program for generating convex and star polygons. You can read about star polygons here: Star polygon – Wikipedia (Links to an external site.)Problem2. Write a program that generates famous fractals: Koch snowflake, Dragon curve, Vicsek snowflake, or other fractals. Here is the list of some of them: List of fractals by Hausdorff dimension – Wikipedia (Links to an external site.)Problem3. Write a program that uses recursion to calculate dynamical systems such as the Lorenz attractor and visualize them using Turtle Graphics. Problem4. Create a game similar to the Turtle Race with additional features (with a timer, buttons to start the race, information about the winner, more advanced stadium layout, etc.)Problem5. Use what you learned about Turtle Graphics in your own projects.You can share your code, ideas, or questions on Canvas in Discussions. Please use the title ‘Labs for Fun’. Enjoy learning Python!

Requirements: 70 | .doc file

The price is based on these factors:

Academic level

Number of pages

Urgency

Basic features

- Free title page and bibliography
- Unlimited revisions
- Plagiarism-free guarantee
- Money-back guarantee
- 24/7 support

On-demand options

- Writer’s samples
- Part-by-part delivery
- Overnight delivery
- Copies of used sources
- Expert Proofreading

Paper format

- 275 words per page
- 12 pt Arial/Times New Roman
- Double line spacing
- Any citation style (APA, MLA, Chicago/Turabian, Harvard)

Delivering a high-quality product at a reasonable price is not enough anymore.

That’s why we have developed 5 beneficial guarantees that will make your experience with our service enjoyable, easy, and safe.

You have to be 100% sure of the quality of your product to give a money-back guarantee. This describes us perfectly. Make sure that this guarantee is totally transparent.

Read moreEach paper is composed from scratch, according to your instructions. It is then checked by our plagiarism-detection software. There is no gap where plagiarism could squeeze in.

Read moreThanks to our free revisions, there is no way for you to be unsatisfied. We will work on your paper until you are completely happy with the result.

Read moreYour email is safe, as we store it according to international data protection rules. Your bank details are secure, as we use only reliable payment systems.

Read moreBy sending us your money, you buy the service we provide. Check out our terms and conditions if you prefer business talks to be laid out in official language.

Read more
## Recent Comments