How to do a specific gap in PYGAME boundaries in top?

124 Views Asked by At

So basically I am trying to remove a gap from the top boundaries (see photo below), but how do I do it? I want to leave this very specific gap.

This is my code for boundaries:

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
BOUNDRY_LEFT = 25
BOUNDRY_TOP = 25
BOUNDRY_RIGHT = SCREEN_WIDTH - 25
BOUNDRY_BOTTOM = SCREEN_HEIGHT - 25

And boundaries collision:

if player_rect.left < BOUNDRY_LEFT:
    player_rect.left = BOUNDRY_LEFT
if player_rect.right > BOUNDRY_RIGHT:
    player_rect.right = BOUNDRY_RIGHT 
if player_rect.top < BOUNDRY_TOP:
    player_rect.top = BOUNDRY_TOP 
if player_rect.bottom > BOUNDRY_BOTTOM:
    player_rect.bottom = BOUNDRY_BOTTOM
1

There are 1 best solutions below

0
On

First of all, you can simplify the boundary checking using pygame.Rect.contains:

test if one rectangle is inside another. Returns true when the argument is completely inside the Rect.

and pygame.Rect.clamp:

moves the rectangle inside another

area_rect = pygame.Rect(BOUNDRY_LEFT, BOUNDRY_TOP, SCREEN_WIDTH, SCREEN_HEIGHT)
if not area_rect.contains(player_rect):
    player_rect = player_rect.clamp(screen_rect)

The gap above is only an exception (logical and) to the condition. Create a pygame.Rect object for the gap and use pygame.Rect.colliderect to test if the player collides with the gap:

area_rect = pygame.Rect(BOUNDRY_LEFT, BOUNDRY_TOP, SCREEN_WIDTH, SCREEN_HEIGHT)
gap_rect = pygame.Rect(SCREEN_WIDTH-200, 0, 200, BOUNDRY_TOP) 

if not area_rect.contains(player_rect) and not gap_rect.colliderect(player_rect):

    player_rect = player_rect.clamp(screen_rect)