--- tags: YMCA --- # Introduction to Python Using Turtle Graphics Welcome coders! In this lesson you'll learn about computer coding using the Python language and the Turtle Graphics *library*, which is a tool built-into Python that lets you draw on the screen. What you will be learning in this lesson is: - What is computer coding? - What is Python and the Turtle Graphics library --- **PART 1: What is the Turtle Library? and How to Use It.** ## What is the Python Turtle Library? `turtle` is a built-in Python library that enables users to create pictures and shapes by providing them with a virtual canvas. The onscreen pen used to draw on the canvas is called the **turtle**, hence the name of the library. The turtle pen can be programmed to draw freeform shapes, predefined shapes, or even to visualize complex math formulas. But that's not all, with some creativity and some python magic, you can even create unique games using the `turtle` library. ### Getting Started with turtle The first step to getting started with this library is to import the turtle library into your coding environment. You do this by using an import statement on the first line of your document. It should look like this: **Try This**: Copy and paste this line of code on line 1: ```python import turtle ``` Great! Next we'll need to create a turtle object which we will use to draw on our canvas. To create a turtle object, simply create a new variable, and assign it the value `turtle.Turtle()` copy and paste this line of code into line 2. ```python t = turtle.Turtle() ``` ## Programming the turtle Now that we've learned how to create a turtle object, let's learn how to make it move! ### Moving the Turtle To move a turtle object around the screen, and make draw, we need to program the turtle by giving different commands.There are four directions that a turtle can move in: - Forward - Backward - Left - Right Each direction has a command to go along with it. Copy this block of code into the next line to see how each command affects the turtle. **Try This:** Copy and paste this block of code into line 4. ```python t.forward(100) t.right(90) t.backward(100) t.left(90) ``` There are two parts to the commands that we just gave our turtle. Let's dissect it a bit. ```python t.forward(100) ``` 1. The first part of the command is the letter '**t**'. If you can recall from line 2; `t = turtle.Turtle()`, hence '**t**' is our turtle object. 2. The second part of the command is the direction the turtle will move in. In the example above, the direction is 'forward'. You can change the word 'forward' to any of the other reserved words to change the turtle's direction. 3. Finally the last part in the command is a set of parentheses with a number in between them: '(100)'. This represents the number of units moving forward or backward or number of degrees the turtle will rotate left or right. When directing the turtle to move `.forward()` or `.backward()`, the turtle will move in the direction it's facing. When telling the turtle to turn, it will turn `.left()` or `.right()` by the degrees it's given in the command's parameters (inside the parentheses). Let's practice moving the turtle some more. Write a couple more commands into your code editor: Click "Save & Run" to make the turtle move once you've given it more commands. **Note:** you can also use the shorthand functions to move the turtle * `t.rt()` == `t.right()` * `t.lt()` == `t.left()` * `t.fd()` == `t.forward()` * `t.bk()` == `t.backward()` **The Turtle's Characteristics** The turtle has certain changeable characteristics such as size, color, and speed. You can change these by giving a command just like before. These *commands* that we've been giving our turtle are called **functions**. The syntax (or the way we write a command) for calling a function on the turtle is called dot-notation which look something like this: ``` variable.function(parameter) ``` Since we imported the `turtle` library and then created a turtle object; we have access to a ton of pre-written functions that are included in the `turtle` library. The two we will use to change the shape and color of our turtle are: * `.shape()` * `.fillcolor()` The first function will change the shape of our pen to one of multiple options: * turtle * arrow * circle * square * triangle * classic By default, the shape of the pen is an arrow. 1. Change the shape of the pen to "turtle" ```python t.shape("turtle") ``` The second function will change the color of the pen. The available colors are pre-defined. 2. Simply call the `.fillcolor()` function on your turtle object and give it the name of a color: ```python t.fillcolor("red") ``` Great! feel free to play with changing the shape and color of the pen. In later lessons we'll go over more customization options for the pen. ### Changing the Pen Size The previous command changed the size of the turtle’s shape only. However, sometimes you may want to change the thickness of your pen's output. You can do this using the following command: ```python .pensize() ``` **Try this:** ```python t.pensize(5) t.forward(100) ``` As you can see, the size of the output is now five times the original size. Try drawing more lines of various sizes and compare the difference in thickness between them. ### Changing the Pen Speed Generally, the turtle moves at a moderate pace. Luckily, you can increase or decrease the speed at which the turtle moves using this command: ```python .speed() ``` The speed can be any number between 0 to 10 (1 being the slowest, 10 being fast, 0 being the fastest speed). You can play around with your code to see how fast or slow the turtle will go. **Try this** copy and paste this code into the next available line: ```python t.speed(1) t.forward(100) t.left(90) t.speed(10) t.forward(100) ``` #### The Coordinate Plane When controlling the turtle, you can also tell the turtle to move to any other arbitrary position on the screen. This is done by using coordinates. Remembering from math class, a coordinate is an x, y value pair usually written as (x, y). If you can imagine the screen being divided into four areas, or quadrants... the turtle will move from its initial position at (0,0), also known as home. To make the turtle move to any other area on the screen, use the `.goto()` function and enter the coordinates to move to: ### Try this: Delete everything below line 2 and copy and paste this line of code into line 4: ```python t.goto(100, 100) ``` to bring the turtle back to its home position, use the `.home()` function. copy and paste this line into line 5. ```python t.home() # this is the same as using t.goto(0, 0) ``` #### Drawing Preset shapes Next, let's learn about drawing some preset shapes. The two preset shapes you can draw with turtles are circle and dot. The functions are `.circle()` and `.dot()` respectively. Both functions only take one parameter for the radius of the shape. Try using both functionsL ```python t.circle(90) t.dot(90) ``` ### Filling in Shapes The last thing we'll look at in this lesson, will be how to fill in shapes. To fill in a shape you will use two functions. `.begin_fill()` and `end_fill()`. ### Try this: ```python t.begin_fill() t.fd(100) t.rt(90) t.fd(100) t.rt(90) t.fd(100) t.rt(90) t.fd(100) t.rt(90) t.end_fill() ``` When you use the `.begin_fill()` function, you are telling the program that you are drawing a shape that will need to be filled in. When the program reaches the line with the `.end_fill()` function, it indicates that this is the end of the shape and it fills it in. # Using Loops Often programmers find themselves repeating multiple lines of code over, and over again. This is also a similar case when having to write commands when working with *turtle*. In this section we are going to use what you already know about loops to write better code! ### for Loops Remember the program from drawing a square? ```python t.fd(100) t.rt(90) t.fd(100) t.rt(90) t.fd(100) t.rt(90) t.fd(100) t.rt(90) ``` This program is 8 lines long. What if we can shorten this to only 3 lines of code? Well, we can thanks to *for loops*! **Try This:** ```python for i in range(4): t.fd(100) t.rt(90) ``` When you run the code, what happens? That's right, a turtle draws a square with only 3 lines of code! To quickly review, **i** is initiated as the counter which is less than our range (which is 4). The program is saying that for as long as ***i*** is in the range of 4 (or less than 4), run the commands `t.fd(100)` and `t.rt(90)`. With every iteration, the counter ***i*** is increased by 1 and the moment ***i*** equals 4 the loop is terminated. ***Reminder:*** *for loops are great when you want to iterate through a list or a set of data.* ### while Loops While loops, although very similar to for loops, are loops that run as long as the condition is still satisfied. For example: ```python n=10 while n <= 40: t.circle(n) n = n+10 ``` In this example, *while* n is less than or equal to 40, draw a circle with the radius of the value of n. Then n will be increased in value by 10. This will happen until the value of n is equal to or greater than 40 at which the loop will be terminated. Try changing the value of n and the amount n is being incremented by. ## Project: Drawing with Loops In this project we are going to give you a couple of example loops that will draw some interesting patterns. You will be able to change the variables to create unique variations of these graphs. *Delete all the code under line 2 to get a clean slate to work on. * ### Spiraling Star ```python star = turtle.Turtle() for i in range(20): star.forward(i * 10) star.right(144) ``` **Notes:** Notice that the turtle is moving forward by a different amount each time. What happens if instead of multiplying i by 10, you multiply it against itself? What if I do star.forward(i * i) instead? ### Lattice Art ```python latice = turtle.Turtle() latice.pencolor("blue") latice.speed(10) for i in range(50): latice.forward(50) latice.left(123) # Let's go counterclockwise this time latice.pencolor("red") for i in range(50): latice.forward(100) latice.left(123) ``` **Notes:** What if you want different colors? You could always try and guess what colors the turtle module can support, but if you want to be precise, you can use the color picker instead. Change the color to a hexadecimal color and see what happens. Also feel free to play with the angle of the turn, or add additional instructions to the for loop. # The Screen Object and Click Events: ### `turtle.Screen()` So far we've been working with `turtle` and may have noticed that sometimes the turtle goes off-screen and we can no longer see it. We have not set-up a screen yet, which would let us see our *turtle* in a wider area. As we begin to work with click events we'll need to create a screen object for which we'll be able to click on. To initiate a screen we'll use the `.Screen()` function like so: ```python # screen object window = turtle.Screen(); ``` This will create a screen object named *window*. Next, we'll need to set up our screen's size. #### `.setup()` To set up the size of the screen, we'll need to call the `.setup()` function on our screen object like so: ```python # setup screen size window.setup(500, 500); ``` &nbsp; `.setup()` can take up to 4 arguments, these are: |argument| definition| |--------|----------| | width | an integer that determines the width of the screen in pixels.| |height | an integer that determines the height of the screen in pixels.| |startx| sets the x starting position, default position is horizontally centered.| |starty| sets the y starting position, default position is vertically centered.| &nbsp; **Note:** `.Screen()` and `.setup()` can be chained together in a single line, like this: ```python window = turtle.Screen().setup(500, 500) ``` &nbsp; ## `turtle.onclick()` The built-in function `.onclick()` is a function used to bind a click event to a mouse-click. This is what the onclick function would look like: Syntax: ```python turtle.onclick(x, y) ``` The `.onclick()` function takes in a coordinate as an argument, hence an **x** and a **y**. **Example:** Copy this code into your editor to try it out. ```python import turtle turtle = turtle.Turtle() def action(x,y): turtle.right(90) turtle.forward(100) # turtle will first move turtle.fd(100) # user clicks on turtle to perform action turtle.onclick(action) ``` ### `turtle.write()` The function `.write()` will write text at the end of the turtle's path.This function takes four parameters and looks something like this: ```python turtle.write(arg, move=False, align="left", font=("Arial", 8, "normal")) ``` - **arg** - is the object to be written to the turtle screen. - **move** - set to True or False, if set to true the pen moves to the bottom-right corner of the text. - **align** - the text alignment, can be set to "left", "center", or "right" - **font** - a triple that takes in (fontname, fontsize, fonttype) as arguments. **try this:** ```python turtle.write("Home = ", True, align="center") turtle.write((0,0), True) ``` #### `str()` The `str()` function returns the string version of the given object. A use case for this is when we want to print a returned number along with other strings. In python we are not able to concatenate strings with integers. For example: ```python number = 5 print("My number is: " + number) # this will print a type error ``` instead we need to do this: ```python number = 5 print("My number is: " + str(number)) # this will print "my number is: 5" ``` ## Project: Turtle Grapher For this project we'll create a simple turtle program using the new functions you've just learned! After completing this project, complete the challenges outline in the **Bonus** section. 1. Let's begin this project by importing the turtle graphics library. ```python import turtle ``` 2. Next, let's create a screen object that we'll be able to click on. ```python # screen object wn = turtle.Screen(); ``` 3. Set up the screen object `window` to be 600 pixels by 600 pixels ```python wn.setup(600, 600) ``` 4. Since we know that we'll be using an `.onclick()` function, we'll need to create a function that will go inside the `.onclick()` function as its argument. Start a function definition and call your function "move_write". For it's arguments it will take in an x, y coordinate. ```python # method to perform action def move_write(x, y): ``` 5. For this function, we want our pen to move towards the direction we click on. Inside the function body write `turtle.goto(x, y)`. ```python def move_write(x, y): turtle.goto(x, y) ``` 6. Next, we're going to make the pen write it's current position, as a coordinate pair, at the end of its movement. Let's add the function that lets the turtle write text at the end of its movement `turtle.write()`. ```python def move_write(x, y): turtle.goto(x, y) turtle.write(str(x)+","+str(y)) ``` 7. We want to have the turtle write its current position, which is a coordinate pair (a pair of numbers). There is a problem though; the `.write()` function can only print out Strings. We need to convert the x, y values to strings. Inside the `.write()` function type the following as the arguments: `str(x)+","+str(y)` ```python def move_write(x, y): turtle.goto(x, y) turtle.write(str(x)+","+str(y)) ``` This will turn the x, y values to strings and write them to the screen. 8. Finally, let's plug in our function inside a click event. To complete the *Turtle Grapher* write the following lines of code: ```python # onclick action wn.onclick(move_write) ``` 9. "Save & Run" the program and click on the screen. Your turtle should travel to the position that you click while drawing a line. #### Bonus: **Great Job!** Now that you have click events down, here are some extra challenges: - Can you make the turtle draw other shapes once it reaches the clicked position? - Make the turtle move to a new position without it drawing a line to its path. Then, make the turtle draw a shape once it reaches its end destination. - Use conditional statements to have the turtle draw a certain shape once it reaches a certain set of coordinates.