Pygame in 90 Minutes - For Beginners

4 min read 1 month ago
Published on Aug 02, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

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

  1. Open Command Prompt or Terminal

    • Windows: Open Command Prompt.
    • Mac/Linux: Open Terminal.
  2. 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
      
  3. 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.

Chapter 2: Setting Up the Game Window

  1. Create a New Python File

    • Name it something other than pygame.py.
  2. 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")
      
  3. 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()
      

Chapter 3: Drawing on the Screen

  1. Fill the Background

    • Use a color constant (e.g., white):
      WHITE = (255, 255, 255)
      win.fill(WHITE)
      
  2. 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))
      
  3. Update the Display

    • After drawing, update the display:
      pygame.display.update()
      

Chapter 4: Player Movement

  1. Define Player Rectangles

    • Create rectangles for player positions:
      yellow = pygame.Rect(100, 200, 55, 40)
      red = pygame.Rect(700, 200, 55, 40)
      
  2. 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
      
  3. 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)
      

Chapter 5: Adding Bullets

  1. Create Bullet List

    • Initialize bullet lists for both players:
      yellow_bullets = []
      red_bullets = []
      
  2. 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)
      
  3. 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)
      
  4. 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)
      

Chapter 6: Collision Detection

  1. 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
      

Chapter 7: Adding Sound Effects

  1. Initialize Sound

    • At the beginning of your code, initialize the mixer:
      pygame.mixer.init()
      
  2. 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')
      
  3. Play Sounds

    • Add sound playback when firing bullets and when a bullet hits:
      bullet_fire_sound.play()
      bullet_hit_sound.play()
      

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!