1
votes

I created a game using pygame, and I wanted to get pygame to give an error like "You can't touch the screen sides", when player touches screen side. I tried searching on the internet, but I didn't find any good results. I thought of adding a block off the screen and when the player touches the block, it gives warning but that took way to long and anyways didn't work. I also don't know how to give alert, and then after giving the alert, to get the game started again. Does anyone know how to do this?

1

1 Answers

1
votes

Define a pygame.Rect object for the player:

player_rect = pygame.Rect(w, y, width, height)

or get a rectangle from the player image (player_image):

player_rect = player_image.get_Rect(topleft = (x, y))

Get the rectangle of the display Surface (screen)

screen_rect = screen.get_rect()

Evaluate if the player is out of the screen:

if player_rect.left < screen_rect.left or player_rect.right < screen_rect.right or \
   player_rect.top < screen_rect.top or player_rect.bottom < screen_rect.bottom:
    printe("You can't touch the screen sides")

See pygame.Rect.clamp() respectively pygame.Rect.clamp_ip():

Returns a new rectangle that is moved to be completely inside the argument Rect.

With this function, an object can be kept completely in the window:

player_rect.clamp_ip(screen_rect)

You can use the clamped rectangle to evaluate whether the player is touching the edge of the window:

screen_rect = screen.get_rect()
player_rect = player_image.get_Rect(topleft = (x, y))

clamped_rect = player_rect.clamp(screen_rect)
if clamped_rect.x != player_rect.x or clamped_rect.y != player_rect.y:
    printe("You can't touch the screen sides")

player_rect = clamped_rect
x, y = player_rect.topleft