Table of Contents
- Introduction
- Prerequisites
- Setup
- Creating the Game Window
- Adding Player Character
- Handling Player Input
- Creating Enemies
- Collision Detection
- Scoring and Game Over
- Conclusion
Introduction
In this tutorial, we will learn how to build a simple game using Pygame, a popular library for game development in Python. By the end of this tutorial, you will have created a basic game with a player character that can move and shoot, enemies that move across the screen, and a scoring system. This tutorial assumes basic knowledge of Python programming.
Prerequisites
Before starting this tutorial, make sure you have the following:
- Python installed on your computer (version 3.6 or above)
- Pygame library installed (
pip install pygame
)
Setup
To begin, create a new directory for your game project. Open a terminal and navigate to the directory. We will start by creating a virtual environment for our project to isolate dependencies.
bash
python -m venv game-env
Activate the virtual environment:
On Windows:
bash
game-env\Scripts\activate
On macOS and Linux:
bash
source game-env/bin/activate
Next, let’s create a new Python file called game.py
in the project directory where we will write the game code.
Creating the Game Window
To start building our game, we will first create a basic game window using Pygame.
First, import the necessary modules:
python
import pygame
Initialize Pygame:
python
pygame.init()
Set the window dimensions:
python
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
Create the game window:
python
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("My Pygame Game")
Next, we need to set up the game loop.
```python
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
window.fill((0, 0, 0))
pygame.display.update()
pygame.quit()
``` We have created the basic structure of our game. Now, let's add a player character.
Adding Player Character
In this step, we will add a player character that can be controlled by the player.
First, let’s create a Player
class:
```python
class Player(pygame.sprite.Sprite):
def init(self, x, y):
super().init()
self.image = pygame.Surface((50, 50))
self.image.fill((255, 0, 0))
self.rect = self.image.get_rect()
self.rect.center = (x, y)
def update(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
self.rect.x -= 5
if keys[pygame.K_RIGHT]:
self.rect.x += 5
if keys[pygame.K_UP]:
self.rect.y -= 5
if keys[pygame.K_DOWN]:
self.rect.y += 5
``` In the game loop, create an instance of the `Player` class and update it:
```python
player = Player(WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2)
all_sprites = pygame.sprite.Group()
all_sprites.add(player)
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
all_sprites.update()
window.fill((0, 0, 0))
all_sprites.draw(window)
pygame.display.update()
pygame.quit()
``` Now we have a player character that can be controlled using the arrow keys. Let's add the ability to shoot.
Handling Player Input
In this step, we will add the ability for the player character to shoot bullets.
First, let’s create a Bullet
class:
```python
class Bullet(pygame.sprite.Sprite):
def init(self, x, y):
super().init()
self.image = pygame.Surface((10, 10))
self.image.fill((0, 255, 0))
self.rect = self.image.get_rect()
self.rect.center = (x, y)
def update(self):
self.rect.y -= 10
``` In the `Player` class, add a method to handle shooting:
```python
def shoot(self):
bullet = Bullet(self.rect.centerx, self.rect.y)
all_sprites.add(bullet)
``` Inside the game loop, add the following code to handle player input:
```python
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
player.shoot()
``` Now the player can shoot bullets by pressing the space key. Let's add enemies that move across the screen.
Creating Enemies
In this step, we will add enemies that move across the screen. The player must avoid colliding with them.
First, let’s create an Enemy
class:
```python
class Enemy(pygame.sprite.Sprite):
def init(self, x, y):
super().init()
self.image = pygame.Surface((30, 30))
self.image.fill((0, 0, 255))
self.rect = self.image.get_rect()
self.rect.center = (x, y)
def update(self):
self.rect.y += 3
``` Inside the game loop, create instances of the `Enemy` class and update them:
```python
enemies = pygame.sprite.Group()
for _ in range(5):
enemy = Enemy(random.randint(0, WINDOW_WIDTH), random.randint(0, 200))
enemies.add(enemy)
all_sprites.add(enemy)
while running:
# ...
all_sprites.update()
enemies.update()
window.fill((0, 0, 0))
all_sprites.draw(window)
pygame.display.update()
pygame.quit()
``` Now we have enemies that move down the screen. Let's implement collision detection.
Collision Detection
In this step, we will check for collisions between the player’s bullets and the enemies. When a collision occurs, we will remove both the bullet and the enemy from the game.
Inside the game loop, add the following code to handle collision detection: ```python bullet_enemy_collisions = pygame.sprite.groupcollide(enemies, bullets, True, True)
for enemy, _ in bullet_enemy_collisions.items():
enemy = Enemy(random.randint(0, WINDOW_WIDTH), random.randint(0, 200))
enemies.add(enemy)
all_sprites.add(enemy)
``` Now, when a bullet collides with an enemy, a new enemy will spawn. Let's add scoring and a game over condition.
Scoring and Game Over
In this step, we will keep track of the player’s score and end the game when the player collides with an enemy. ```python player_score = 0 game_over = False
while running:
# ...
for enemy in pygame.sprite.spritecollide(player, enemies, False):
game_over = True
if game_over:
# Game over logic
break
window.fill((0, 0, 0))
all_sprites.draw(window)
pygame.display.update()
pygame.quit()
``` Now the game will end when the player collides with an enemy. We can also keep track of the player's score by incrementing `player_score` when a bullet hits an enemy.
Conclusion
In this tutorial, we learned how to build a game using Pygame. We covered creating the game window, adding a player character, handling player input, creating enemies, implementing collision detection, scoring, and a game over condition. You can enhance the game by adding sound effects, more levels, or additional features.
Remember to experiment and have fun with your game development projects! Happy coding!