Search code examples
pythonpgzero

Transparent rectangles in PyGame Zero


I'm using screen.draw.rect() to draw rectangles with PyGame Zero. They will be used as a collision map on a game. I can't work out how to make them transparent though. The only documentation I can find is for the standard PyGame library, which is slightly different but enough for it not to work.

import pgzrun

TILE_SIZE = 64
TILES_WIDE = 8
TILES_HIGH = 8
WIDTH = TILE_SIZE * TILES_WIDE
HEIGHT = TILE_SIZE * TILES_HIGH

tiles = ["empty", "wall", "water"]

mapSheet = [
    [0, 1, 1, 1, 1, 1, 1, 0],
    [1, 0, 0, 0, 0, 0, 0, 1],
    [1, 0, 1, 0, 0, 1, 0, 1],
    [1, 0, 0, 0, 0, 0, 0, 1],
    [1, 0, 1, 0, 0, 1, 0, 1],
    [1, 0, 0, 1, 1, 0, 0, 1],
    [1, 0, 0, 0, 0, 0, 0, 1],
    [0, 1, 1, 1, 1, 1, 1, 0]
]

def draw():
    screen.clear()
    for rows in range(TILES_HIGH):
        for cols in range(TILES_WIDE):
            x = cols * TILE_SIZE
            y = rows * TILE_SIZE
            if mapSheet[rows][cols] == 1:
                mybox = Rect((x, y), (TILE_SIZE, TILE_SIZE))
                screen.draw.rect(mybox, (255, 255, 255))
               
# Start
pgzrun.go()

Solution

  • Following the link provided by Rabbid76 above, I've modified the code and include it below. This creates rectangles which are 50% transparent.

    import pgzrun
    import pygame
    
    TILE_SIZE = 64
    TILES_WIDE = 8
    TILES_HIGH = 8
    WIDTH = TILE_SIZE * TILES_WIDE
    HEIGHT = TILE_SIZE * TILES_HIGH
    
    tiles = ["empty", "wall", "water"]
    
    mapSheet = [
        [0, 1, 1, 1, 1, 1, 1, 0],
        [1, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 1, 0, 0, 1, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 1, 0, 0, 1, 0, 1],
        [1, 0, 0, 1, 1, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 1],
        [0, 1, 1, 1, 1, 1, 1, 0]
    ]
    
    def draw():
        screen.clear()
        alphaSurface = pygame.Surface((TILE_SIZE, TILE_SIZE))
        for rows in range(TILES_HIGH):
            for cols in range(TILES_WIDE):
                x = cols * TILE_SIZE
                y = rows * TILE_SIZE
                if mapSheet[rows][cols] == 1:
                    alphaSurface.set_alpha(128) # Set transparency
                    alphaSurface.fill((255, 255, 255))
                    screen.blit(alphaSurface, (x,y))
                   
    # Start
    pgzrun.go()