Table of Contents
- Introduction
- Prerequisites
- Setup
- Creating the Game Window
- Drawing the Spaceship
- Moving the Spaceship
- Shooting Bullets
- Creating the Asteroids
- Collisions and Score
- Game Over
- Conclusion
Introduction
In this tutorial, we will be building a clone of the classic game Asteroids using Python and the Pygame library. By the end of this tutorial, you will have a functioning game where the player controls a spaceship, shoots bullets, avoids asteroids, and earns points for destroying them.
Prerequisites
Before starting this tutorial, it would be helpful to have a basic understanding of Python programming. Familiarity with object-oriented programming concepts will also be beneficial. Additionally, you should have Python and Pygame installed on your computer.
Setup
To begin, make sure you have Python installed on your system. You can download the latest version of Python from the official Python website and follow the installation instructions.
Once Python is installed, we need to install the Pygame library. Open a terminal or command prompt and run the following command:
pip install pygame
Pygame should now be installed and ready for use.
Creating the Game Window
First, we need to import the necessary modules and set up the game window. Create a new Python script and add the following code: ```python import pygame import sys
# Initialize Pygame
pygame.init()
# Set up the game window
window_width = 800
window_height = 600
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("Asteroids Game Clone")
# Game loop
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
``` In this code, we import the `pygame` and `sys` modules. We initialize Pygame and set up the game window with a width of 800 pixels and a height of 600 pixels. We also set the window's caption to "Asteroids Game Clone".
Next, we enter the game loop, which will continuously update the game and handle user input. Inside the loop, we check for the QUIT
event, which is triggered when the user closes the game window. If this event is detected, we call pygame.quit()
to gracefully exit the game.
Finally, we call pygame.display.update()
to update the game window.
Run the script, and you should see a window titled “Asteroids Game Clone”. You can close the window to exit the game.
Drawing the Spaceship
Now let’s draw the spaceship on the game window. Add the following code after the game window setup: ```python # Load spaceship image spaceship_img = pygame.image.load(“spaceship.png”)
# Get spaceship dimensions
spaceship_width = spaceship_img.get_width()
spaceship_height = spaceship_img.get_height()
# Set initial spaceship position
spaceship_x = window_width / 2 - spaceship_width / 2
spaceship_y = window_height - spaceship_height - 10
# Game loop
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Draw spaceship
window.blit(spaceship_img, (spaceship_x, spaceship_y))
pygame.display.update()
``` In this code, we load the spaceship image using `pygame.image.load()`. Make sure to replace `"spaceship.png"` with the file path of your spaceship image.
Next, we get the width and height of the spaceship image using the get_width()
and get_height()
methods. These values will be used to calculate the spaceship’s position and handle collisions later.
We set the initial position of the spaceship to be centered horizontally and near the bottom of the window. The spaceship’s x-coordinate is calculated as window_width / 2 - spaceship_width / 2
, and the y-coordinate is set to window_height - spaceship_height - 10
.
Inside the game loop, we use window.blit()
to draw the spaceship image onto the game window at the specified position (spaceship_x, spaceship_y)
.
Run the script, and you should see the spaceship displayed on the game window.
Moving the Spaceship
Now let’s add keyboard controls to move the spaceship. Add the following code inside the game loop, right after the event handling code:
python
# Move spaceship
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
spaceship_x -= 5
if keys[pygame.K_RIGHT]:
spaceship_x += 5
if keys[pygame.K_UP]:
spaceship_y -= 5
if keys[pygame.K_DOWN]:
spaceship_y += 5
In this code, we use pygame.key.get_pressed()
to get the state of all keyboard keys. We check the state of the arrow keys (pygame.K_LEFT
, pygame.K_RIGHT
, pygame.K_UP
, pygame.K_DOWN
), and if a key is pressed, we update the spaceship’s position accordingly.
The spaceship is moved by 5 pixels in each direction.
Run the script, and you should be able to control the spaceship’s movement using the arrow keys.
Shooting Bullets
Now let’s implement the ability to shoot bullets from the spaceship. Add the following code inside the game loop, after the spaceship movement code: ```python # Shoot bullets if keys[pygame.K_SPACE]: bullet_x = spaceship_x + spaceship_width / 2 bullet_y = spaceship_y bullet_radius = 2 bullet_color = (255, 255, 255) # White
pygame.draw.circle(window, bullet_color, (int(bullet_x), int(bullet_y)), bullet_radius)
``` In this code, we check if the spacebar key (`pygame.K_SPACE`) is pressed. If it is, we set the initial position of the bullet to be at the center of the spaceship's x-coordinate and at the top of the spaceship's y-coordinate. The bullet's radius is set to 2 pixels, and the color is set to white using RGB values.
We use pygame.draw.circle()
to draw the bullet on the game window. The position of the bullet is specified as (int(bullet_x), int(bullet_y))
to convert the float coordinates to integer values.
Run the script, and you should be able to shoot bullets from the spaceship by pressing the spacebar.
Creating the Asteroids
Next, let’s add asteroids to the game that the player needs to avoid. Add the following code after the bullet shooting code: ```python # Draw asteroids asteroid_x = 100 asteroid_y = 100 asteroid_width = 50 asteroid_height = 50 asteroid_color = (255, 0, 0) # Red
pygame.draw.rect(window, asteroid_color, (asteroid_x, asteroid_y, asteroid_width, asteroid_height))
``` In this code, we set the initial position of the asteroid to `(100, 100)` and its dimensions to `50x50` pixels. The color of the asteroid is set to red using RGB values.
We use pygame.draw.rect()
to draw a rectangle representing the asteroid on the game window. The position and dimensions of the rectangle are specified as (asteroid_x, asteroid_y, asteroid_width, asteroid_height)
.
Run the script, and you should see an asteroid displayed on the game window.
Collisions and Score
Now let’s handle collisions between the bullets and the asteroids, as well as keep track of the player’s score. Add the following code after the asteroid drawing code: ```python # Handle collisions bullet_rect = pygame.Rect(bullet_x, bullet_y, bullet_radius * 2, bullet_radius * 2) asteroid_rect = pygame.Rect(asteroid_x, asteroid_y, asteroid_width, asteroid_height)
if bullet_rect.colliderect(asteroid_rect):
score += 1
asteroid_x = 900
asteroid_y = 900
bullet_x = -100
bullet_y = -100
# Draw score
font = pygame.font.Font(None, 36)
score_text = font.render("Score: " + str(score), True, (255, 255, 255)) # White
window.blit(score_text, (10, 10))
``` In this code, we first create `pygame.Rect` objects representing the boundaries of the bullet and the asteroid. The bullet's rectangle has dimensions `bullet_radius * 2` so that it matches the diameter of the bullet.
We then check if the rectangles collide using the colliderect()
method. If a collision occurs, we increment the score, move the asteroid and bullet off-screen (to prevent further collisions), and update the score text.
We use pygame.font.Font()
to create a font object with a size of 36 pixels. We render the score text using font.render()
with the text “Score: “ concatenated with the score value. The rendered text is then displayed on the game window using window.blit()
.
Run the script, and you should see the score being updated when the bullet collides with the asteroid.
Game Over
Lastly, let’s add a game over condition if the spaceship collides with an asteroid. Add the following code after the collision handling code: ```python # Check game over spaceship_rect = pygame.Rect(spaceship_x, spaceship_y, spaceship_width, spaceship_height)
if spaceship_rect.colliderect(asteroid_rect):
game_over = True
if game_over:
game_over_text = font.render("Game Over", True, (255, 255, 255)) # White
window.blit(game_over_text, (window_width / 2 - game_over_text.get_width() / 2, window_height / 2))
pygame.display.update()
pygame.time.wait(2000) # Pause for 2 seconds
pygame.quit()
sys.exit()
``` In this code, we create a `pygame.Rect` object to represent the boundaries of the spaceship. We then check if the spaceship rectangle collides with the asteroid rectangle. If a collision occurs, we set the `game_over` flag to True.
We add another conditional block to check if game_over
is True. If it is, we render the “Game Over” text and display it at the center of the game window. We then update the game window, pause for 2 seconds using pygame.time.wait()
, and exit the game.
Run the script, and you should see the “Game Over” text displayed when the spaceship collides with an asteroid. The game will exit after a 2-second pause.
Conclusion
In this tutorial, we have built a clone of the classic Asteroids game using Python and the Pygame library. We started by setting up the game window, then added the spaceship, implemented movement controls, and shooting bullets. We also added asteroids, handled collisions, kept track of the player’s score, and implemented a game-over condition.
This tutorial has provided a basic introduction to Pygame and game development in Python. From here, you can expand on the game by adding more features, such as multiple levels, power-ups, and sound effects. You can also experiment with different game mechanics to make it your own.
Remember to have fun and keep exploring the world of Python game development!