• Python Game Design - Turtle Graphics

The Turtle API

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.

Abstraction

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.

python turtle documentation screenshot

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.

Next
© Tynker, 2020

Setting up the Screen

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

The turtle Screen

We 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

Change the Background Color

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
1
 
1
​
Previous Next
© Tynker, 2020

Creating Turtles

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.

Creating A Turtle Object

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
1
 
1
​
Previous Next
© Tynker, 2020

What Is a Sprite?

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.

Creating a Sprite with Turtle

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

Setting a Sprite's Initial Values

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)

Clone the Prototype

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)

Do It Yourself

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
6
 
1
import turtle
2
​
3
t = turtle.Turtle()
4
t.shape("square")
5
t.penup()
6
t.speed(0)
Previous Next
© Tynker, 2020

Moving and Drawing with the Turtle

Now we will learn how to move and draw with turtles.

Instructions

  1. Launch the built-in Code Editor and follow the tutorial to learn about the Python turtle.
  2. Remember to save your progress so that you can work on it later. Access your work from here or from "My Projects" in your Tynker account.
Start Project
Previous Next
© Tynker, 2020

Writing Your Own Functions

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.

Defining A Function

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.

A Simple 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
4
 
1
def print_message():
2
    print("Calling the print_message function")
3
​
4
print_message()

Function Parameters

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
5
 
1
def spare_change(quarters, dimes, nickels, pennies):
2
    cents = quarters * 25 + dimes * 10 + nickels * 5 + pennies
3
    return cents
4
​
5
print(spare_change(1, 2, 5, 8))

Function Scope

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.

Global Scope

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
5
 
1
i = 0
2
def print_global():
3
    print(i)
4
​
5
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
7
 
1
i = 0
2
def change_global():
3
    global i
4
    i += 1
5
    print(i)
6
​
7
change_global()

Local Scope

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
5
 
1
def change_local():
2
    i = 0
3
    i += 1
4
change_local()
5
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.

Defining and Calling Turtle Functions

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
12
 
1
import turtle
2
​
3
def create_turtle(x, y):
4
    t = turtle.Turtle()
5
    t.shape("square")
6
    t.penup()
7
    t.speed(0)
8
    t.goto(x,y)
9
​
10
create_turtle(0,0)
11
create_turtle(100,0)
12
create_turtle(0,100)
Previous Next
© Tynker, 2020

Responding to Key Presses

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.

The onkey() Method

We'll use onkey() to add interactivity into our Turtle projects.

onkey() has two parameters.

  • The first parameter is the function you want to run in response to a key press
  • The second is the name of the key to want to bind the function to. You can use keys like "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")

Listen for Keys

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.

Detecting a Key Press

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
13
 
1
import turtle
2
​
3
screen = turtle.Screen()
4
​
5
square = turtle.Turtle()
6
square.penup()
7
square.speed(0)
8
​
9
def f():
10
    square.write("You pressed the up key")
11
​
12
screen.onkey(f, "Up")
13
screen.listen()

A Turtle That Moves

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
14
 
1
import turtle
2
​
3
screen = turtle.Screen()
4
​
5
square = turtle.Turtle()
6
square.shape("square")
7
square.penup()
8
square.speed(0)
9
​
10
def f():
11
    square.forward(10)
12
​
13
screen.onkey(f, "Right")
14
screen.listen()
Previous Next
© Tynker, 2020

Asteroids

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.

Asteroid Example

Instructions

  1. Launch the built-in Code Editor and follow the tutorial to make the simple game.
  2. Remember to save your progress so that you can work on it later. Access your work from here or from "My Projects" in your Tynker account.
Start Project
Previous Next
© Tynker, 2020

Turtle Review

Let's review what you've learned in this lesson about the turtle module.

Using the Turtle Tool

In order to use turtle graphics, you must always start by importing the module.

xxxxxxxxxx
 
import turtle

The turtle Screen

The 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

Background Color

You can change the screen's background color by calling the bgcolor() function from the screen object (such as screen.bgcolor("blue")).

Turtle Object

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

Sprites

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

Movement

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)

Pen Drawing

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").

Built-in Shapes

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')
Previous Next
© Tynker, 2020

User Interaction Review

Review what you have learned so far in this lesson about user interaction.

Defining a Function

Function definitions begin with the keyword def followed by a function name and parentheses, and then a colon.

  • The code segment within each function is indented.
  • A return command exits a function and can pass a value back to the caller.

Here is an example of a function definition:

xxxxxxxxxx
 
def function_name():
    # commands
    return

Function Parameters

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)

Function Scope

A scope defines the visibility of an identifier (a variable or function). You only need to know two levels of scope: global and local.

Global Scope

Identifiers defined in global scope can be seen by all of the program. All identifiers defined outside of functions are in global scope.

Local 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.

The onkey() Function

The turtle screen has a method called onkey() that allows you to program a function to respond to any key.

  • onkey() takes two parameters:
  • The first parameter is the function you want to perform in response to the key press.
  • The second parameter requires a string of the key name. Some examples of valid names are: "Space", "a", "w", or "Up".
Previous Done
© Tynker, 2020
Sign in
Don't have an account?