Pygame in 90 Minutes - For Beginners
Table of Contents
Introduction
This tutorial is designed for beginners who want to learn how to create a simple two-player game using Pygame in Python. Throughout this guide, you'll learn how to set up Pygame, create a game window, manage player movement, handle collisions, and implement sound effects. By the end of this tutorial, you'll have a functional game that you can expand upon.
Chapter 1: Installing Pygame
-
Open Command Prompt or Terminal
- Windows: Open Command Prompt.
- Mac/Linux: Open Terminal.
-
Install Pygame
- Use the following command to install Pygame:
pip install pygame
- If you encounter issues, try:
pip3 install pygame
- Alternatively, use:
python -m pip install pygame
- For Mac, you might need:
python3 -m pip install pygame
- Use the following command to install Pygame:
-
Verify Installation
- Create a new Python file and write:
import pygame
- Run the file. If you see a welcome message from Pygame, the installation is successful.
- Create a new Python file and write:
Chapter 2: Setting Up the Game Window
-
Create a New Python File
- Name it something other than
pygame.py
.
- Name it something other than
-
Import Pygame and Set Up Window
- Define the width and height of the game window:
WIDTH, HEIGHT = 900, 500
- Initialize Pygame and create the window:
pygame.init() win = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("First Game")
- Define the width and height of the game window:
-
Create the Game Loop
- Set up the main loop to keep the window open:
run = True while run: for event in pygame.event.get(): if event.type == pygame.QUIT: run = False pygame.quit()
- Set up the main loop to keep the window open:
Chapter 3: Drawing on the Screen
-
Fill the Background
- Use a color constant (e.g., white):
WHITE = (255, 255, 255) win.fill(WHITE)
- Use a color constant (e.g., white):
-
Draw Spaceships
- Load the spaceship images:
yellow_spaceship = pygame.image.load('assets/spaceship_yellow.png') red_spaceship = pygame.image.load('assets/spaceship_red.png')
- Scale the images:
yellow_spaceship = pygame.transform.scale(yellow_spaceship, (55, 40)) red_spaceship = pygame.transform.scale(red_spaceship, (55, 40))
- Draw the spaceships:
win.blit(yellow_spaceship, (100, 200)) win.blit(red_spaceship, (700, 200))
- Load the spaceship images:
-
Update the Display
- After drawing, update the display:
pygame.display.update()
- After drawing, update the display:
Chapter 4: Player Movement
-
Define Player Rectangles
- Create rectangles for player positions:
yellow = pygame.Rect(100, 200, 55, 40) red = pygame.Rect(700, 200, 55, 40)
- Create rectangles for player positions:
-
Handle Movement
- Create a function to handle player movement:
def handle_movement(keys, player_rect): if keys[pygame.K_a]: player_rect.x -= 5 if keys[pygame.K_d]: player_rect.x += 5 if keys[pygame.K_w]: player_rect.y -= 5 if keys[pygame.K_s]: player_rect.y += 5
- Create a function to handle player movement:
-
Call Movement in Main Loop
- Inside the main loop, check for key presses:
keys = pygame.key.get_pressed() handle_movement(keys, yellow) handle_movement(keys, red)
- Inside the main loop, check for key presses:
Chapter 5: Adding Bullets
-
Create Bullet List
- Initialize bullet lists for both players:
yellow_bullets = [] red_bullets = []
- Initialize bullet lists for both players:
-
Fire Bullets
- Check for control key presses and append bullets to the list:
if event.type == pygame.KEYDOWN: if event.key == pygame.K_LCTRL and len(yellow_bullets) < 3: bullet = pygame.Rect(yellow.x + yellow.width, yellow.y + yellow.height // 2 - 2, 10, 5) yellow_bullets.append(bullet) elif event.key == pygame.K_RCTRL and len(red_bullets) < 3: bullet = pygame.Rect(red.x, red.y + red.height // 2 - 2, 10, 5) red_bullets.append(bullet)
- Check for control key presses and append bullets to the list:
-
Move Bullets
- Update bullet positions and remove them if they go off-screen:
for bullet in yellow_bullets: bullet.x += 7 if bullet.x > WIDTH: yellow_bullets.remove(bullet) for bullet in red_bullets: bullet.x -= 7 if bullet.x < 0: red_bullets.remove(bullet)
- Update bullet positions and remove them if they go off-screen:
-
Draw Bullets
- Draw bullets in the main loop:
for bullet in yellow_bullets: pygame.draw.rect(win, (255, 255, 0), bullet) for bullet in red_bullets: pygame.draw.rect(win, (255, 0, 0), bullet)
- Draw bullets in the main loop:
Chapter 6: Collision Detection
- Check for Collisions
- Inside the bullet handling logic, check if bullets collide with either player:
for bullet in yellow_bullets: if bullet.colliderect(red): yellow_bullets.remove(bullet) red_health -= 1 # Assuming you have defined red_health
- Inside the bullet handling logic, check if bullets collide with either player:
Chapter 7: Adding Sound Effects
-
Initialize Sound
- At the beginning of your code, initialize the mixer:
pygame.mixer.init()
- At the beginning of your code, initialize the mixer:
-
Load Sound Effects
- Load the sound effects for firing and hitting:
bullet_fire_sound = pygame.mixer.Sound('assets/gun_silencer.mp3') bullet_hit_sound = pygame.mixer.Sound('assets/grenade_plus_one.mp3')
- Load the sound effects for firing and hitting:
-
Play Sounds
- Add sound playback when firing bullets and when a bullet hits:
bullet_fire_sound.play() bullet_hit_sound.play()
- Add sound playback when firing bullets and when a bullet hits:
Conclusion
You have successfully learned how to create a simple two-player game using Pygame, including installing the library, setting up a game window, handling player movement, firing bullets, detecting collisions, and adding sound effects. This foundational knowledge will allow you to expand and enhance your game further. Consider exploring additional features like scoring systems, animations, or more complex game mechanics to deepen your understanding of Pygame. Happy coding!