'Easy Way To Detect Collisions With Window Edge In Pygame?

I am making a non-scrolling platformer in pygame, and am wondering if there is an easy way to detect collisions with the edge of the window, without creating four rects offscreen. Does anyone know if there is? Thanks.



Solution 1:[1]

If you're testing collisions for Rects, you can use

if (Rect.left < 0 or Rect.right > (window width) or 
      Rect.top < 0 or Rect.bottom > (window height)):
    collision = True # do whatever collision code you need here

If you need a way to get the screen size, you can use

width, height = pygame.display.get_surface().get_size()

and then use the width and height variables.

Solution 2:[2]

You can use pygame.Rect.contains to test if a rectangle is entirely inside another rectangle:

window_rect = screen.get_rect()
if not window_rect.contains(object_rec):
    # [...]

Use pygame.Rect.colliderect to test if a rectangle is entirely outside another rectangle:

window_rect = screen.get_rect()
if not window_rect.colliderect(object_rec):
    # [...]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ethan Ray
Solution 2 Rabbid76