Table of Contents
Overview
In this tutorial, we will build a basic game using Python and Pygame library. We will create a simple game where the player controls a character and avoids enemies while trying to collect items. By the end of this tutorial, you will have a working game with player movement, enemy creation, collision detection, and scoring.
Prerequisites
To follow along with this tutorial, you should have basic knowledge of Python programming language. Familiarity with object-oriented programming concepts will also be helpful. Additionally, you will need to have Pygame library installed on your system. If you haven’t installed it already, you can do so by running the following command:
pip install pygame
Setup
Before we start building the game, let’s first set up a new Python project. Here are the steps:
- Create a new directory for your project.
- Open a text editor or an integrated development environment (IDE) of your choice.
- Create a new Python file in the project directory and save it with a “.py” extension.
Now we are ready to start building our game!
Building the Game
Step 1: Creating a Window
The first step is to create a window where our game will be displayed. Pygame provides a pygame.display.set_mode()
function for this purpose. Here’s some code to get started:
```python
import pygame
# Initialize Pygame
pygame.init()
# Set the window dimensions
width = 800
height = 600
window = pygame.display.set_mode((width, height))
# Set the window title
pygame.display.set_caption("My Game")
# Game loop
running = True
while running:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Update game logic
# Render game graphics
pygame.display.flip()
# Quit Pygame
pygame.quit()
``` In the code above, we import the Pygame library and initialize it using `pygame.init()`. We then set the dimensions of our game window and create it using `pygame.display.set_mode()`. We also set the window title using `pygame.display.set_caption()`. Finally, we enter a game loop that handles events, updates the game logic, and renders the graphics.
Step 2: Adding Images
Next, let’s add some images to our game. The pygame.image.load()
function allows us to load image files. Here’s an example of loading and displaying an image:
```python
player_image = pygame.image.load(“player.png”)
player_rect = player_image.get_rect()
player_rect.center = (width // 2, height // 2)
# Game loop
while running:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Update game logic
# Render game graphics
window.fill((0, 0, 0))
window.blit(player_image, player_rect)
pygame.display.flip()
``` In the code above, we load an image file called "player.png" using `pygame.image.load()`. We then create a rectangle object (`player_rect`) that represents the position and size of the player image. We set its initial position to the center of the window. Inside the game loop, we clear the window, blit (draw) the player image onto the window at the position specified by `player_rect`, and then update the display using `pygame.display.flip()`.
Step 3: Player Movement
Now let’s add movement to our player character. We can achieve this by updating the position of player_rect
based on keyboard input. Here’s how to handle player movement:
```python
# Game loop
while running:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Update game logic
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player_rect.x -= 5
if keys[pygame.K_RIGHT]:
player_rect.x += 5
if keys[pygame.K_UP]:
player_rect.y -= 5
if keys[pygame.K_DOWN]:
player_rect.y += 5
# Render game graphics
window.fill((0, 0, 0))
window.blit(player_image, player_rect)
pygame.display.flip()
``` In the code above, we use `pygame.key.get_pressed()` to get the current state of all keyboard keys. We then check if the arrow keys are pressed (`pygame.K_LEFT`, `pygame.K_RIGHT`, `pygame.K_UP`, `pygame.K_DOWN`) and update the position of `player_rect` accordingly. This allows the player to move the character around the window.
Step 4: Enemy Creation
Let’s add some enemies to our game. We can use a list to keep track of multiple enemy objects. Here’s an example: ```python class Enemy: def init(self, x, y): self.image = pygame.image.load(“enemy.png”) self.rect = self.image.get_rect() self.rect.center = (x, y)
enemies = []
enemies.append(Enemy(100, 100))
enemies.append(Enemy(200, 200))
# Game loop
while running:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Update game logic
# Render game graphics
window.fill((0, 0, 0))
for enemy in enemies:
window.blit(enemy.image, enemy.rect)
window.blit(player_image, player_rect)
pygame.display.flip()
``` In the code above, we define an `Enemy` class that represents an enemy object with its image and position. We create a list `enemies` and append two enemy objects to it. Inside the game loop, we iterate over the `enemies` list and draw each enemy image onto the window.
Step 5: Collision Detection
Next, let’s implement collision detection between the player and enemies. We can use the colliderect()
method of the rectangle objects to check if they are overlapping. Here’s how to handle collision detection:
```python
# Game loop
while running:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Update game logic
for enemy in enemies:
if player_rect.colliderect(enemy.rect):
# Handle collision logic (e.g., game over)
# Render game graphics
window.fill((0, 0, 0))
for enemy in enemies:
window.blit(enemy.image, enemy.rect)
window.blit(player_image, player_rect)
pygame.display.flip()
``` In the code above, we iterate over the `enemies` list and check if the player rectangle collides with each enemy rectangle using `colliderect()`. If a collision is detected, you can handle the collision logic as needed (e.g., end the game).
Step 6: Scoring
Lastly, let’s add scoring to our game. We can display the score on the game window and increment it whenever the player collects an item. Here’s how to implement scoring: ```python font = pygame.font.Font(None, 36) score = 0
# Game loop
while running:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Update game logic
for enemy in enemies:
if player_rect.colliderect(enemy.rect):
# Handle collision logic (e.g., game over)
score -= 10
if score < 0:
score = 0
# Render game graphics
window.fill((0, 0, 0))
for enemy in enemies:
window.blit(enemy.image, enemy.rect)
window.blit(player_image, player_rect)
# Render score
score_text = font.render("Score: " + str(score), True, (255, 255, 255))
window.blit(score_text, (10, 10))
pygame.display.flip()
``` In the code above, we create a `Font` object to render text on the screen. We also initialize a `score` variable to keep track of the player's score. Inside the game loop, we check for collisions between the player and enemies, and decrement the score if a collision occurs. We then render the score text on the window using `render()` method of the font object.
Conclusion
Congratulations! You have successfully built a basic game using Python and Pygame library. You have learned how to create a game window, load and display images, handle player movement, create enemies, detect collisions, and implement scoring. This tutorial only scratches the surface of what you can achieve with Pygame, but it provides a solid foundation to build upon. Experiment with different features and mechanics to make your game more interesting and challenging. Happy game development!