0

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()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
wibbleface
  • 119
  • 14
  • You cannot draw a transparent shape with either Pygame Zero or Pygame. You have to create a transparent surface and draw the shape on that surface. The Pygame solution is explained here: [Draw a transparent rectangles and polygons in pygame](https://stackoverflow.com/questions/6339057/draw-a-transparent-rectangles-and-polygons-in-pygame/64630102#64630102). It should be possible to use these functions in Pygame Zero. – Rabbid76 Jun 15 '22 at 20:55
  • When looking for a Pygame Zero solution you need to use the [tag:pgzero] tag instead of the [tag:pygame] tag. – Rabbid76 Jun 15 '22 at 20:56

1 Answers1

0

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()
wibbleface
  • 119
  • 14