In this Pygame article we want to learn How to Detect Collisions in Pygame, Collisions are an important part of many games and applications, and Pygame provides a number of tools for handling them. In this article we want to talk that how to handle collisions in Pygame.
This is the complete code for this article
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 |
import pygame import random # Initialize Pygame pygame.init() # Set up the screen screen_width = 800 screen_height = 600 screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption("Collision Detection Example") # Set up the clock clock = pygame.time.Clock() # Define colors white = (255, 255, 255) black = (0, 0, 0) red = (255, 0, 0) # Define the Player sprite class class Player(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = pygame.Surface((50, 50)) self.image.fill(white) self.rect = self.image.get_rect() self.rect.center = (screen_width // 2, screen_height // 2) self.speed = 5 def update(self): # Move the player keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: self.rect.x -= self.speed elif keys[pygame.K_RIGHT]: self.rect.x += self.speed if keys[pygame.K_UP]: self.rect.y -= self.speed elif keys[pygame.K_DOWN]: self.rect.y += self.speed # Keep the player on the screen if self.rect.left < 0: self.rect.left = 0 elif self.rect.right > screen_width: self.rect.right = screen_width if self.rect.top < 0: self.rect.top = 0 elif self.rect.bottom > screen_height: self.rect.bottom = screen_height # Define the Enemy sprite class class Enemy(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = pygame.Surface((30, 30)) self.image.fill(red) self.rect = self.image.get_rect() self.rect.x = random.randrange(screen_width - self.rect.width) self.rect.y = random.randrange(-100, -40) self.speed = random.randrange(1, 5) def update(self): # Move the enemy down the screen self.rect.y += self.speed # Respawn the enemy if it goes off the bottom of the screen if self.rect.top > screen_height + 10: self.rect.x = random.randrange(screen_width - self.rect.width) self.rect.y = random.randrange(-100, -40) self.speed = random.randrange(1, 5) # Set up the sprite groups all_sprites = pygame.sprite.Group() enemies = pygame.sprite.Group() # Create the player sprite and add it to the all_sprites group player = Player() all_sprites.add(player) # Create the enemy sprites and add them to the all_sprites and enemies groups for i in range(10): enemy = Enemy() all_sprites.add(enemy) enemies.add(enemy) # Game loop running = True while running: # Handle events for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Update the sprites all_sprites.update() # Detect collisions between the player and enemies collisions = pygame.sprite.spritecollide(player, enemies, True) for enemy in collisions: # Handle the collision player.speed -= 1 # Draw the screen screen.fill(black) all_sprites.draw(screen) pygame.display.flip() # Wait for the next frame clock.tick(60) # Quit Pygame pygame.quit() |
This code is simple example of a Pygame program that demonstrates collision detection between the player and enemy sprites. it starts by importing the Pygame module and the random module. after that it initializes Pygame and sets up the screen with a width of 800 pixels and a height of 600 pixels. screen is also given a caption of Collision Detection Example.
After that the clock is set up to help regulate the frame rate of the game. three colors are defined using RGB values.
Two sprite classes are defined for the player and the enemy. Player class has an image with dimensions of 50×50 pixels and is centered on the screen. It also has a speed value of 5 pixels per frame. enemy class has an image with dimensions of 30×30 pixels and is randomly placed at the top of the screen with a random speed between 1 and 5 pixels per frame.
After that sprite groups are set up. all_sprites group contains both the player and the enemies. enemies group only contains the enemies.
our program also enters a game loop, where it first handles events like the user closing the window. after that it updates all of the sprites and checks for collisions between the player and the enemies using the spritecollide method.
If a collision is detected, the player speed is decreased by 1 pixel per frame. screen is then filled with black and all of the sprites are drawn on the screen. and lastly Pygame display is updated with the latest changes and the program waits for the next frame. once the user closes the window or quits the program, Pygame is properly quit.
Run the code and this will be the result

Learn More on Pygame
- Pygame Display: Setting Up Game Window
- Pygame Init: Getting Started with Pygame
- Pygame Caption: Giving Your Game a Title
- How to Draw Rectangles on Pygame
- How to Control Pygame Frame Rate
- How to Handle User Input in Pygame
- How to Detect Key Presses in Pygame
- How to Work with Fonts in Pygame
- How to Display Image in Pygame
- How add Sound Effect in Pygame