In this lesson you will learn how to use a software library stored in what is called a Python module. In this case, the module is called turtle
, and it contains a large set of functions for moving a virtual turtle around a screen.
By learning the turtle
application programming interface, or API, you can easily create complex programs. We will teach you several useful turtle
functions in this lesson, but if you want to learn more, you can check out the official Python turtle
API here.
An Application Programming Interface tells you how the functions in a library behave and can be used. APIs can be very long and difficult to read all at once, but you should take a look at the turtle
API now. In it, you will see documentation for the turtle
module that will help you to understand the behaviors of turtle
and how to use its functions.
turtle
produces output on a graphics canvas, rather than as text to the console. There are many different ways to produce output, such as tactile, audio, visual, or text.
Let's start to display graphics on the screen and draw objects. This is an exciting first step towards making real, playable games!
In order to use turtle
graphics, you must import the turtle
module. A module is a bunch of code that someone else wrote and packaged for us to use. We can import all kinds of other cool functions with import statements, but for now, all we need is turtle
.
xxxxxxxxxx
import turtle
turtle
ScreenWe want to create a canvas on which to draw, something like a blank sheet of paper. The turtle's screen is the window where you'll be able to draw using turtles.
You can draw on it, display images, and change its color. But in order to use the screen, you must first define it using the turtle.Screen()
function.
xxxxxxxxxx
screen = turtle.Screen() # get the turtle screen
Now that we've imported the turtle
module and defined a screen, we can start making changes to that screen.
Let's try bgcolor()
. Notice how it's a method of the screen. By passing different strings to this method, you can change the color of the screen.
xxxxxxxxxx
screen.bgcolor("blue")
Try changing the background to your favorite color!
Write your code in the editor below.
xxxxxxxxxx
The name turtle
comes from a virtual "turtle" that crawls around the screen.
We'll use the turtle like a digital pen, drawing wherever it goes.
You can create a new turtle using the turtle.Turtle()
method. In the code below, we create a turtle called t
, then define its shape to be a "square"
.
xxxxxxxxxx
t = turtle.Turtle() #create a new turtle
t.shape("square")
When you run this code, you'll see a square appear in the middle of the screen. Now the turtle is ready to receive movement commands and draw.
You can create as many turtles as you want with turtle.Turtle()
. Just give them new variable names.
Write your code in the editor below.
xxxxxxxxxx
Most games have characters that perform actions on the screen.
We call these characters sprites. Sprites can move around the screen and interact with one another. A sprite might include the player character, coins for the player to collect, and bad guys for the player to avoid. Or they can be decorations, like the background of the game.
Let's look at how we can create and clone sprites with the Turtle module.
When working with Python's Turtle module, you can use a turtle as your sprite. So you can just create a new sprite using turtle.Turtle() as we've done before.
xxxxxxxxxx
sprite = turtle.Turtle()
You can set the sprite's initial values so that it looks and behaves exactly as you want.
Often you'll want to use the penup()
and speed(0)
commands so that the sprite doesn't leave a trail and moves as fast as possible, without any animations.
xxxxxxxxxx
sprite = turtle.Turtle()
#make sure it is in penup state so it does not leave a trail.
sprite.penup()
#make sure it moves as fast as possible.
sprite.speed(0)
Once you've created one sprite and set its initial values in a way that you like, you can create copies of the sprite by cloning the original. In this way, your original sprite acts like a prototype.
Any clones of the original will inherit the same properties of the original. In the example below, we create a prototype called sprite
, then make two clones of it called actor1
and actor2
using the clone()
method.
xxxxxxxxxx
import turtle
sprite = turtle.Turtle()
sprite.hideturtle()
sprite.penup()
sprite.speed(0)
actor1 = sprite.clone()
actor1.showturtle()
actor1.goto(-100,170)
actor2 = sprite.clone()
actor2.showturtle()
actor2.goto(100,170)
The code below currently creates a single sprite using the create_turtle()
command. Modify the code to create multiple sprites using clone()
, and move each clone to a different location while also giving it a different color.
xxxxxxxxxx
import turtle
t = turtle.Turtle()
t.shape("square")
t.penup()
t.speed(0)
Now we will learn how to move and draw with turtles.
So far, we've mostly been using functions that other programmers have already written for us, like turn_left()
, and print()
.
But you can also create functions of your own. A function is a set of repeatable code, a set of instructions that you can call upon again and again in your programs. For example, imagine you're coding a board game. You might write a function that "rolled the dice" since that's an action that will need to happen again and again.
Functions make your program more organized and allows you to reuse code easily.
To create your own function, you must define it. Function definitions begin with the keyword def
followed by the function name, parentheses ()
, and a colon :
.
The code that is indented afterwards is the function body. This is the code that will run when you use your function. Defining a function won't run it, though. When you use your function later in code, that's calling the function.
Let's look at the basic syntax to start.
xxxxxxxxxx
def function_name():
statement1
statement2
Here, we've defined a function called function_name()
. statement1
and statement2
are in the body of the function.
Let's define a real function we can run. The one below defines a function called print_message()
and its task is to print out Calling the print_message function
to the screen.
After the function body ends, we call the print_message()
function. If we didn't, the function's code would not be executed.
Click on the run button to try it out.
xxxxxxxxxx
def print_message():
print("Calling the print_message function")
print_message()
Functions can be defined with parameters. Parameters allow programmers to give extra information to a function to tell it how to behave. For example, when you were playing with turtle
, you used the forward(100)
method to tell the turtle to move forward 100
steps.
Parameters allow external information to be passed into functions. This allows for greater control and flexibility in your programs.
To use parameters, you add parameters into the function definition. You can define one or several parameters for your custom function to take. Give your parameters unique names and separate them with commas. You can then refer to them in your function body. In the example below, we pass the parameters to print()
.
xxxxxxxxxx
def function_name(parameter1, parameter2, parameter3):
print(parameter1)
print(parameter2)
print(parameter3)
Here's an example of a function that takes the number of each type of coin you have (how many quarters, dimes, nickels, and pennies you have) and returns how much money the coins add up to.
xxxxxxxxxx
def spare_change(quarters, dimes, nickels, pennies):
cents = quarters * 25 + dimes * 10 + nickels * 5 + pennies
return cents
print(spare_change(1, 2, 5, 8))
Now that you've seen the basics on creating a function, let's explore a concept called scope. Scope defines the visibility of an identifier (like a function or variable) within a section of code.
Within your functions, you can use any code you like, including all the concepts you've learned about so far, including variables, conditionals, and so on. But you'll want to understand how scope works, as it can create unexpected errors when you're writing your own functions.
Identifiers defined in global scope can be seen by all of the program. All identifiers defined outside of functions are in the global scope.
xxxxxxxxxx
i = 0
def print_global():
print(i)
print_global()
Since i
is in global scope, the function print_global()
can see and read from it.
However, if you need to change the variable i
, you must tell the function that it is global.
This is done using the global
keyword.
xxxxxxxxxx
i = 0
def change_global():
global i
i += 1
print(i)
change_global()
Identifiers defined inside functions are in local scope and can only be seen by other code of the same scope, that is, code in the same function body.
xxxxxxxxxx
def change_local():
i = 0
i += 1
change_local()
print(i)
If you run this code, you'll see that the code gives an error. This is because i
is only defined in local scope and can't be seen outside the change_local()
function.
Here is a function that creates a turtle at position (x, y) specified by the parameters x
and y
.
Click on the run button to try it out.
xxxxxxxxxx
import turtle
def create_turtle(x, y):
t = turtle.Turtle()
t.shape("square")
t.penup()
t.speed(0)
t.goto(x,y)
create_turtle(0,0)
create_turtle(100,0)
create_turtle(0,100)
If we want to make games, we need a way to detect and respond to key presses in your programs so that the player can control the game.
The turtle
module has a few built-in ways to detect key presses. We'll create functions that respond to user input in this section.
onkey()
MethodWe'll use onkey()
to add interactivity into our Turtle projects.
onkey()
has two parameters.
"a"
or "w"
. Or you can use "Up" and "Down" and so forth for the arrow keys.It looks like this:
xxxxxxxxxx
screen.onkey(func_name, "key")
For example, you might define a function called jump()
, then bind the Space key to that function. You'd write that like this:
xxxxxxxxxx
screen.onkey(jump, "Space")
Once you've used onkey()
, we have to add another line of code to activate the turtle screen's listener. Otherwise, the screen won't "hear" the keys being pressed. You use it like this:
xxxxxxxxxx
screen.listen()
Notice that the listen()
method does not require a parameter, and you only need to call it once to activate a turtle screen's listener, even if you have more than one onkey()
method.
The example below defines a function called f
and its task is to write "You pressed the up key"
to the screen. We use a new Turtle method called write()
to write text using Turtle graphics.
The first 8 lines of the code set up the turtle
module, screen and turtle. Then we define the f()
function at line 9.
Notice the last two lines of code, how we use the onkey()
method. It takes f
as a parameter, then "Up"
as its second parameter, which is the name of the key we want to detect. Finally, we use listen()
to make sure the screen will respond.
Click on the run button, then press the up arrow key to try it out.
xxxxxxxxxx
import turtle
screen = turtle.Screen()
square = turtle.Turtle()
square.penup()
square.speed(0)
def f():
square.write("You pressed the up key")
screen.onkey(f, "Up")
screen.listen()
Let's try to make the turtle respond to a key press.
In this example, we will make a turtle move forward using the right arrow key. Click on the run button, then press the right arrow key to try it out.
xxxxxxxxxx
import turtle
screen = turtle.Screen()
square = turtle.Turtle()
square.shape("square")
square.penup()
square.speed(0)
def f():
square.forward(10)
screen.onkey(f, "Right")
screen.listen()
In this lesson you will learn how to code the user interaction for a simple game: Asteroids. When you are done, you will add some additional features.
Let's review what you've learned in this lesson about the turtle
module.
In order to use turtle
graphics, you must always start by importing the module.
xxxxxxxxxx
import turtle
turtle
ScreenThe screen object is where your turtles will draw and move.
In order to draw with turtles, you must define the screen using the turtle.Screen()
function.
xxxxxxxxxx
screen = turtle.Screen() # get the turtle screen
You can change the screen's background color by calling the bgcolor()
function from the screen
object (such as screen.bgcolor("blue")
).
To create a turtle, use the turtle.Turtle()
method and assign its output to a variable.
You can make as many turtles as you want. This line of code creates a turtle named bob
.
xxxxxxxxxx
bob = turtle.Turtle()
A sprite is a graphical representation of an object in a program. When you're using the turtle module to create games, a turtle object can be a sprite.
xxxxxxxxxx
sprite = turtle.Turtle()
When you're using a turtle object as a sprite, you should set it with these properties:
xxxxxxxxxx
sprite.penup() # make the turtle object not draw a line as it moves
sprite.speed(0) # make the turtle's movement as fast as possible
If you need copies of a single sprite, you can create copies by cloning it. You can create one "prototype" sprite with the correct initial values, then clone it like so:
xxxxxxxxxx
actor = sprite.clone()
You can interpret and control the movement and position of a turtle using (x, y)
coordinates. The center of the screen is at position (0,0)
. The x axis increases towards the right while the y axis increases upwards.
These methods can be called to move a turtle around:
xxxxxxxxxx
forward(x) # moves the turtle object forward by x pixels
goto(x,y) # moves to (x, y) regardless of current position
left(x) # turns the turtle object left/counterclockwise by x degrees
right(x) # turns the turtle object right/clockwise by x degrees
Methods are called using dot notation from the turtle that will move:
xxxxxxxxxx
bob.forward(100)
You can control whether the turtle object draws a line as it moves with penup()
and pendown()
methods.
You can change the color of the line as well with pen.color("blue")
.
You can set the turtle's shape with the shape()
method.
The turtle library provides 6 different built-in shapes you can use out of the box:
'arrow', 'turtle', 'circle', 'square', 'triangle', 'classic'
For example, the following code changes the shape of the turtle bob
to a triangle:
xxxxxxxxxx
bob.shape('triangle')
Review what you have learned so far in this lesson about user interaction.
Function definitions begin with the keyword def
followed by a function name and parentheses, and then a colon.
Here is an example of a function definition:
xxxxxxxxxx
def function_name():
# commands
return
Functions can also be defined with parameters, which allow external information to be passed into functions.
Parameters are added within the parentheses of function definitions. Parameter names should be unique and separated with commas.
Here is an example of a function that takes three parameters and prints them out:
xxxxxxxxxx
def function_name(parameter1, parameter2, parameter3):
print(parameter1)
print(parameter2)
print(parameter3)
A scope defines the visibility of an identifier (a variable or function). You only need to know two levels of scope: global and local.
Identifiers defined in global scope can be seen by all of the program. All identifiers defined outside of functions are in global scope.
Identifiers defined inside functions are in local scope and can only be seen by code of the same scope. A variable defined inside a function cannot be accessed outside of that function.
onkey()
FunctionThe turtle
screen has a method called onkey()
that allows you to program a function to respond to any key.
onkey()
takes two parameters:"Space"
, "a"
, "w"
, or "Up"
.