知方号

知方号

Build a Python Turtle Game: Space Invaders Clone – Real Python

Build a Python Turtle Game: Space Invaders Clone by Stephen Gruppetta Mar 20, 2024 basics python

Table of Contents

Demo: A Python Turtle Space Invaders GameProject OverviewPrerequisitesStep 1: Set Up the Turtle Game With a Screen and a Laser CannonCreate the ScreenCreate the Laser CannonStep 2: Move the Cannon Using KeysMove the Turtle ObjectMove the Entire Laser CannonControl When Items Are DisplayedPrevent the Laser Cannon From Leaving the ScreenStep 3: Shoot Lasers With the SpacebarCreate LasersCreate the Game Loop to Move the LasersRemove Lasers That Leave the ScreenStep 4: Create and Move the AliensSpawn New AliensMove the AliensStep 5: Determine When Lasers Hit AliensStep 6: End the GameStep 7: Add a Timer and a ScoreCreate a TimerAdd the ScoreStep 8: Improve the Cannon’s MovementStep 9: Set the Game’s Frame RateConclusionNext Steps Remove ads

In this tutorial, you’ll use Python’s turtle module to build a Space Invaders clone. The game Space Invaders doesn’t need any introduction. The original game was released in 1978 and is one of the most recognized video games of all time. It undeniably defined its own video game genre. In this tutorial, you’ll create a basic clone of this game.

The turtle module you’ll use to build the game is part of Python’s standard library, and it enables you to draw and move sprites on the screen. The turtle module is not a game-development package, but it gives instructions about creating a turtle game, which will help you understand how video games are built.

In this tutorial, you’ll learn how to:

Design and build a classic video gameUse the turtle module to create animated spritesAdd user interaction in a graphics-based programCreate a game loop to control each frame of the gameUse functions to represent key actions in the game

This tutorial is ideal for anyone who is familiar with the core Python topics and wants to use them to build a classic video game from scratch. You don’t need to be familiar with the turtle module to work through this tutorial. You can download the code for each step by clicking on the link below:

Get Your Code: Click here to download the free sample code that shows you how to build a Python turtle game.

In the next section, you can have a look at the version of the game you’ll build as you follow the steps outlined in this tutorial.

Demo: A Python Turtle Space Invaders Game

You’ll build a simplified version of the classic Space Invaders game and control the laser cannon with the keys on your keyboard. You’ll shoot lasers from the cannon by pressing the spacebar, and aliens will appear at regular intervals at the top of the screen and move downwards. Your task is to shoot the aliens before they reach the bottom of the screen. The game ends when one alien reaches the bottom.

This is what your turtle game will look like when you complete this tutorial:

Here you can see the main game play for this game, as the laser cannon moves back and forth and shoots the falling aliens. The game also displays the elapsed time and the number of aliens shot down on the screen.

Remove adsProject Overview

In this project, you’ll start by creating the screen that will contain the game. In each step, you’ll create game components such as the laser cannon, lasers, and aliens, and you’ll add the features required to make a functioning game.

To create this turtle game, you’ll work through the following steps:

Create the game screen and the laser cannonMove the cannon left and right using keysShoot lasers with the spacebarCreate aliens and move them towards the bottom of the screenDetermine when a laser hits an alienEnd the game when an alien reaches the bottomAdd a timer and a scoreImprove the cannon’s movement to make the game smootherSet the game’s frame rate

You’ll start with a blank screen, and then see the game come to life one feature at a time as you work through each step in this tutorial.

Prerequisites

To complete this tutorial, you should be comfortable with the following concepts:

Repeating code using for loops and while loopsUsing if statements to control what happens in different conditionsDefining functions to encapsulate codeUsing lists to store multiple items

You don’t need to be familiar with Python’s turtle to start this tutorial. However, you can read an overview of the turtle module to find out more about the basics.

If you don’t have all of the prerequisite knowledge before you start, that’s okay! In fact, you might learn more by going ahead and getting started! You can always stop and review the resources linked here if you get stuck.

Step 1: Set Up the Turtle Game With a Screen and a Laser Cannon

You can’t have a game without a screen where all the action happens. So, the first step is to create a blank screen. Then, you can add sprites to represent the items in the game. In this project, you can run your code at any point to see the game in its current state.

You can download the code as it’ll look at the end of this step from the folder named source_code_step_1/ in the link below:

Get Your Code: Click here to download the free sample code that shows you how to build a Python turtle game.

It’s time to take the first step in setting up your game with the turtle module and create the screen.

Create the Screen

To start, create a new file and import the turtle module:

Python turtle_invaders.py import turtleturtle.done() Copied!

You call turtle.done(), which displays the window and keeps it open. This line should always be the last line in any program that uses turtle. This will prevent the program from terminating when it reaches the last line. To stop the program, you close the window by clicking the close window icon in the upper corner of the window, just as you would with any other window in your operating system.

Although this code creates and displays a screen, you can explicitly create the screen in your code and assign it to a variable name. This approach lets you customize the screen’s size and color:

Python turtle_invaders.py import turtlewindow = turtle.Screen()window.setup(0.5, 0.75)window.bgcolor(0.2, 0.2, 0.2)window.title("The Real Python Space Invaders")turtle.done() Copied!

You use floats as arguments for .setup(), which sets the screen size as a fraction of your computer screen. The window’s width is 50 percent of your screen’s width, and its height is 75 percent of your screen’s height. You can experiment with using pixel values to set the screen dimensions by using integers instead of floats as arguments in .setup().

The default color mode in the turtle module requires the red, green, and blue components to be floats in the range [0, 1]. You should also update the text in the title bar. When you run this code, you’ll see this screen:

This version has a dark background but you can customize your game with your preferred colors. Now, you’re ready to create the laser cannon.

Remove adsCreate the Laser Cannon

Just like you can’t have a game without a screen, you can’t have a space invaders clone game without a laser cannon. To set up the cannon, you create a Turtle object using turtle.Turtle(). Each independent item in the game needs its own Turtle object.

When you create a Turtle object, it’s located at the center of the screen and faces right. The default image is an arrow showing the object’s heading. You can change these values using Turtle methods:

Python turtle_invaders.py import turtlewindow = turtle.Screen()window.setup(0.5, 0.75)window.bgcolor(0.2, 0.2, 0.2)window.title("The Real Python Space Invaders")# Create laser cannoncannon = turtle.Turtle()cannon.penup()cannon.color(1, 1, 1)cannon.shape("square")turtle.done() Copied!

The cannon is now a white square. You call cannon.penup() so that the Turtle object doesn’t draw a line when you move it. You can see the cannon when you run the code:

However, you want the cannon to be at the bottom of the screen. Here’s how you set the cannon’s new position:

Python turtle_invaders.py import turtlewindow = turtle.Screen()window.setup(0.5, 0.75)window.bgcolor(0.2, 0.2, 0.2)window.title("The Real Python Space Invaders")LEFT = -window.window_width() / 2RIGHT = window.window_width() / 2TOP = window.window_height() / 2BOTTOM = -window.window_height() / 2FLOOR_LEVEL = 0.9 * BOTTOM# Create laser cannoncannon = turtle.Turtle()cannon.penup()cannon.color(1, 1, 1)cannon.shape("square")cannon.setposition(0, FLOOR_LEVEL)turtle.done() Copied!

You define the edges of the screen using window.window_height() and window.window_width() since these values will be different on different computer setups. The center of the screen has the coordinates (0, 0). So, you divide the width and height by two, to get the x- and y-coordinates for the four edges.

You also define FLOOR_LEVEL as 90 percent of the y-coordinate of the bottom edge. Then, place the cannon at this level using .setposition() so that it’s raised slightly from the bottom of the screen.

Remember, this is a clone of a 1970s game, so all you need are simple graphics! You can draw the cannon by stretching the shape of the turtle into rectangles of different sizes using .turtlesize() and calling .stamp() to leave a copy of this shape on the screen. The code below only shows the section of the code that has changed:

Python turtle_invaders.py # ...# Draw cannoncannon.turtlesize(1, 4) # Basecannon.stamp()cannon.sety(FLOOR_LEVEL + 10)cannon.turtlesize(1, 1.5) # Next tiercannon.stamp()cannon.sety(FLOOR_LEVEL + 20)cannon.turtlesize(0.8, 0.3) # Tip of cannoncannon.stamp()cannon.sety(FLOOR_LEVEL)turtle.done() Copied!

When you run this code, you’ll see the cannon at the bottom of the screen:

Your next task is to bring in some interactivity so you can move the cannon left and right.

Step 2: Move the Cannon Using Keys

In the previous step, you wrote code to draw the cannon on the screen. But a game needs a player who can interact with it. So now it’s time to learn about keybindings, so you can use the keyboard to move the cannon.

You can download the code as it’ll look at the end of this step from the folder named source_code_step_2/ in the link below:

Get Your Code: Click here to download the free sample code that shows you how to build a Python turtle game.

To start, you’ll familiarize yourself with key techniques used in animation.

Remove adsMove the Turtle Object

You can bind a function to a key using window.onkeypress(). The keypress calls the function bound to that key. You can define two functions to move the cannon left and right, and bind them to the Left and Right arrow keys on your keyboard:

Python turtle_invaders.py import turtleCANNON_STEP = 10# ...def move_left(): cannon.setx(cannon.xcor() - CANNON_STEP)def move_right(): cannon.setx(cannon.xcor() + CANNON_STEP)window.onkeypress(move_left, "Left")window.onkeypress(move_right, "Right")window.onkeypress(turtle.bye, "q")window.listen()turtle.done() Copied!

Did you notice that you used the function names move_left and move_right without parentheses as arguments for .onkeypress()? If you add parentheses, the program calls the function when it executes the line with .onkeypress(), and it binds the function’s return value to the key. The functions move_left() and move_right() return None, so if you include parentheses, the arrow keys will remain inactive.

The functions to move the cannon use CANNON_STEP, which you define at the top of your code. The name is written using uppercase letters to show that this is a constant value you use to configure the game. Try changing this value to see how this will affect the game.

You also bring the focus to the screen using window.listen() so that keypress events are collected by the program. By default, the turtle module doesn’t use computing resources to listen for keypresses while the program is running. Calling window.listen() overrides this default. If the keys don’t work when you run a turtle game, make sure that you included .listen() as it’s easy to forget about when using .onkeypress().

Now that you’re familiar with keybindings, you’ll add a feature to quit the program by binding the Q key to turtle.bye. As you did with the previous functions, you don’t add parentheses to turtle.bye even though it’s a function. Make sure you use a lowercase q because if you use an uppercase letter in the code, you’ll need to press Shift+Q to quit the program.

Now when you run the program, you’re able to press the right and left arrow keys to move the Turtle object.

Note: Functions used as arguments for .onkeypress() can’t accept any required arguments. Although the functions can have a return statement, you can’t access the returned data in your program since these functions are called from within .onkeypress().

Here’s what the output looks like at this stage:

This is not quite the behavior you want. Notice how only one part of the drawing moves when you press the arrow keys. This is the sprite representing the Turtle object. The rest of the drawing is the result to the .stamp() calls in the section of code where you draw the laser cannon.

Move the Entire Laser Cannon

Every time you move the laser cannon, you can clear the previous drawing and redraw the cannon in the new location. To avoid repetition, you can move the code to draw the cannon into a function draw_cannon(). In the following code, most of the lines in draw_cannon() are the same lines you had in the previous version, but now they’re indented:

Python turtle_invaders.py # ...def draw_cannon(): cannon.clear() cannon.turtlesize(1, 4) # Base cannon.stamp() cannon.sety(FLOOR_LEVEL + 10) cannon.turtlesize(1, 1.5) # Next tier cannon.stamp() cannon.sety(FLOOR_LEVEL + 20) cannon.turtlesize(0.8, 0.3) # Tip of cannon cannon.stamp() cannon.sety(FLOOR_LEVEL)def move_left(): cannon.setx(cannon.xcor() - CANNON_STEP) draw_cannon()def move_right(): cannon.setx(cannon.xcor() + CANNON_STEP) draw_cannon()window.onkeypress(move_left, "Left")window.onkeypress(move_right, "Right")window.onkeypress(turtle.bye, "q")window.listen()draw_cannon()turtle.done() Copied!

When you call cannon.clear(), all the drawings made by cannon are deleted from the screen. You call draw_cannon() in both move_left() and move_right() to redraw the cannon each time you move it. You also call draw_cannon() in the main section of the program to draw the cannon at the start of the game.

Here’s what the game looks like now:

The whole laser cannon moves when you press the left or right arrow keys. The function draw_cannon() deletes and redraws the three rectangles that make up the cannon.

However, the movement of the cannon is not smooth and can glitch if you try to move it too rapidly, as you can see in the second part of the video. You can fix this issue by controlling when items are drawn on the screen in the turtle module.

Remove adsControl When Items Are Displayed

The turtle module displays several small steps when Turtle objects move. When you move cannon from its initial central position to the bottom of the screen, you can see the square move downwards to its new position. When you redraw the cannon, the Turtle object needs to move to several locations, change shape, and create a stamp of that shape.

These actions take time, and if you press an arrow key during this drawing process, the Turtle object moves before it has time to complete the drawing.

This problem becomes even more noticeable when there are more events occurring in the game. Now is a good time to fix this issue. You can prevent any changes from being displayed on the screen by setting window.tracer(0).

The program will still change the coordinates of a Turtle object and its heading, but will not display the changes on the screen. You can control when the screen is updated by calling window.update(). This gives you control over when to update the screen.

You can call window.tracer(0) right after you create the screen and window.update() in draw_cannon():

Python turtle_invaders.py import turtleCANNON_STEP = 10window = turtle.Screen()window.tracer(0)# ...def draw_cannon(): # ... window.update()# ... Copied!

Now there are no glitches when you move the cannon, and the initial placement of cannon from the center to the bottom is no longer visible. Here’s this turtle game so far:

You’ll improve how smoothly the cannon moves later in this tutorial. In the next step, you’ll fix another problem. Notice how towards the end of the video, you can see the laser cannon moving out of the screen when the left arrow key is pressed too many times. You need to prevent the cannon from leaving the screen so it can hold center ground and defend the planet from the invading aliens!

Prevent the Laser Cannon From Leaving the Screen

The functions move_left() and move_right() are called each time the player presses one of the arrow keys to move the laser cannon left or right. To check whether the laser cannon has reached the edge of the screen, you can add an if statement. Instead of using LEFT and RIGHT, which are the edges of the screen, you’ll include a gutter to stop the cannon just before it reaches the edges:

Python turtle_invaders.py # ...LEFT = -window.window_width() / 2RIGHT = window.window_width() / 2TOP = window.window_height() / 2BOTTOM = -window.window_height() / 2FLOOR_LEVEL = 0.9 * BOTTOMGUTTER = 0.025 * window.window_width()# ...def move_left(): new_x = cannon.xcor() - CANNON_STEP if new_x >= LEFT + GUTTER: cannon.setx(new_x) draw_cannon()def move_right(): new_x = cannon.xcor() + CANNON_STEP if new_x TOP: laser.clear() laser.hideturtle() lasers.remove(laser) turtle.turtles().remove(laser) window.update()turtle.done() Copied!

Notice how the for loop iterates through a copy of lasers, since it’s best not to loop through a list that’s being changed within the same for loop.

At this point, you can add print(len(turtle.turtles())) and print(len(lasers)) to the game loop to confirm that lasers are removed from these lists when they leave the screen.

Good job! You’re ready to create aliens and move them down the screen.

Remove adsStep 4: Create and Move the Aliens

It’s the quiet before the storm. The laser cannon sits idle at the moment since there are no invading aliens to shoot at. The time has come to add the aliens to your game.

You’ve already done most of the hard work to create and move the aliens since you can deal with aliens similarly to lasers. But there are some minor differences:

New aliens spawn every few seconds instead of when the player presses a key.Aliens appear at the top of the screen in a random x-position instead of at the tip of the cannon.The shape and color of the aliens are different from lasers.

Other than these slight differences, the rest of the code will mirror the code you wrote to create and move lasers.

You can download the code as it’ll look at the end of this step from the folder named source_code_step_4/ in the link below:

Get Your Code: Click here to download the free sample code that shows you how to build a Python turtle game.

To start this part of the project, you’ll create aliens to appear at regular time intervals. Once this is in place, you can focus on moving them.

Spawn New Aliens

To start, you define the new function create_alien() and a list to store the aliens:

Python turtle_invaders.py import randomimport turtle# ...lasers = []aliens = []# ...def create_alien(): alien = turtle.Turtle() alien.penup() alien.turtlesize(1.5) alien.setposition( random.randint( int(LEFT + GUTTER), int(RIGHT - GUTTER), ), TOP, ) alien.shape("turtle") alien.setheading(-90) alien.color(random.random(), random.random(), random.random()) aliens.append(alien)# ... Copied!

You place the aliens at the top of the screen in a random x-position. The aliens face downwards. You also assign random values for the red, green, and blue color components so that every alien has a random color.

Aliens appear at regular time intervals in this turtle game. You can import the time module and set a timer to spawn a new alien:

Python turtle_invaders.py import randomimport timeimport turtleCANNON_STEP = 10LASER_LENGTH = 20LASER_SPEED = 10ALIEN_SPAWN_INTERVAL = 1.2 # Seconds# ...# Game loopalien_timer = 0while True: # ... # Spawn new aliens when time interval elapsed if time.time() - alien_timer > ALIEN_SPAWN_INTERVAL: create_alien() alien_timer = time.time() window.update()turtle.done() Copied!

The code now spawns a new alien every 1.2 seconds. You can adjust this value to make the game harder or easier. Here’s the game so far:

Aliens are spawning at regular intervals, but they’re stuck at the top of the screen. Next, you’ll learn how to move the aliens around the screen.

Move the Aliens

This is where you’ll move all of the aliens in the game loop’s list of aliens:

Python turtle_invaders.py import randomimport timeimport turtleCANNON_STEP = 10LASER_LENGTH = 20LASER_SPEED = 10ALIEN_SPAWN_INTERVAL = 1.2 # SecondsALIEN_SPEED = 2# ...# Game loopalien_timer = 0while True: # ... # Move all aliens for alien in aliens: alien.forward(ALIEN_SPEED) window.update()turtle.done() Copied!

The aliens are now continuously moving down:

If the aliens aren’t moving at the right speed, you can adjust their speed by using a different value for ALIEN_SPEED. Keep in mind that the speed of the game will vary depending on the system you’re working on. You’ll set the frame rate of the game in the last step of this tutorial, so you don’t need to worry about the speed for now.

This turtle game is looking closer to completion, but there are a still a few key steps you need to take before this is a game you can play. The first of these steps is to detect when a laser hits an alien.

Remove adsStep 5: Determine When Lasers Hit Aliens

You probably noticed in the previous video that the lasers were going right through the aliens without affecting them. This behavior won’t stop the alien invasion! Currently, the program is not checking whether a laser hits an alien. So you’ll need to update the code to deal with this important game feature.

You can download the code as it’ll look at the end of this step from the folder named source_code_step_5/ in the link below:

Get Your Code: Click here to download the free sample code that shows you how to build a Python turtle game.

In each frame of the game, you’re likely to have several lasers flying upwards and several aliens falling downwards. So you need to check whether any of the lasers hit any of the aliens. In this part of tutorial, you’ll apply a simple technique to deal with this issue—you’ll check the distance of each laser from each alien to detect any hits.

Granted this is not the most efficient option, but it’s good enough for this simplified version of space invaders.

In the game loop, you already have a loop iterating through the list of lasers. You can add another loop to iterate through each alien for every laser:

Python turtle_invaders.py # ...while True: # Move all lasers for laser in lasers.copy(): move_laser(laser) # Remove laser if it goes off screen if laser.ycor() > TOP: laser.clear() laser.hideturtle() lasers.remove(laser) turtle.turtles().remove(laser) # Check for collision with aliens for alien in aliens.copy(): if laser.distance(alien) TOP: remove_sprite(laser, lasers) break # Check for collision with aliens for alien in aliens.copy(): if laser.distance(alien)

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至lizi9903@foxmail.com举报,一经查实,本站将立刻删除。