Menu
CoddyTech

See-Through Pixels

Part of the Sprites and Images section of Coddy's Pygame journey. Lesson 5 of 36.

An image file is always a rectangle, but an enemy ship is not. The pixels around it are transparent: each pixel of a PNG has a fourth number, its alpha, from 0 (see-through) to 255 (solid).

The starter loads the three enemies with convert(), which throws the alpha away: every see-through pixel turns black, and each enemy sits in a black box. convert_alpha() keeps the alpha, so only the solid pixels cover the window. Use it for anything that is not a solid rectangle.

The Rect is still the whole rectangle. Outline it to see the box the picture takes up:

rect = red.get_rect(topleft=(128, 200))
screen.blit(red, rect)
pygame.draw.rect(screen, (90, 90, 120), rect, 1)

The last number, 1, draws a 1 pixel outline instead of filling the Rect. Look at the gaps between the outline and the ship. Two Rects can overlap while the pictures inside them do not touch, and a collision test with Rects still says they hit. Chapter 5 fixes that.

challenge icon

Challenge

Easy
  1. Load the three enemies with .convert_alpha() instead of .convert(), so the black boxes go.
  2. After each enemy, outline its Rect in (90, 90, 120), 1 pixel wide. The enemies stay at (128, 200), (288, 200) and (448, 200).

Try it yourself

import pygame

pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Three Enemies")
clock = pygame.time.Clock()

red = pygame.image.load("assets/images/enemy_red.png").convert()
green = pygame.image.load("assets/images/enemy_green.png").convert()
yellow = pygame.image.load("assets/images/enemy_yellow.png").convert()

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill((20, 22, 40))
    screen.blit(red, (128, 200))
    screen.blit(green, (288, 200))
    screen.blit(yellow, (448, 200))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Sprites and Images

Practice on your own: Pygame playground