user7704093
user7704093

Reputation:

How can I stop a character in pygame from leaving the edge of the screen?

I have created a small program in pygame where the player controls a blue square moving around the screen, but I want to stop the player from moving past the edge of the screen. Here is the code I have so far, how can I do this?

import pygame

pygame.init()
screen = pygame.display.set_mode((800, 600))
done = False
x = 30
y = 30

clock = pygame.time.Clock()

while not done:
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                        done = True
                if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                        is_blue = not is_blue


    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_UP]: y -= 5
    if pressed[pygame.K_DOWN]: y += 5
    if pressed[pygame.K_LEFT]: x -= 5
    if pressed[pygame.K_RIGHT]: x += 5

    screen.fill((0, 0, 0))
    color = (0, 128, 255)
    pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60))

    pygame.display.flip()
    clock.tick(60)

Upvotes: 3

Views: 7350

Answers (4)

skrx
skrx

Reputation: 20438

pygame.Rects have a clamp (and clamp_ip) method which you can use to limit the movement area. So create a rect with the size of the screen (called screen_rect here) and a rect for the player (player_rect) and call the clamp_ip method after each movement to keep it inside of the screen area.

import pygame as pg


pg.init()
screen = pg.display.set_mode((640, 480))
BG_COLOR = pg.Color(30, 30, 50)


def main():
    clock = pg.time.Clock()
    image = pg.Surface((50, 30))
    image.fill(pg.Color('dodgerblue'))
    pg.draw.rect(image, pg.Color(40, 220, 190), (0, 0, 49, 29), 2)
    player_rect = image.get_rect(topleft=(200, 200))
    # This pygame.Rect has the dimensions of the screen and
    # is used to clamp the player_rect to this area.
    screen_rect = screen.get_rect()
    speed = 5

    while True:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                return

        pressed = pg.key.get_pressed()
        if pressed[pg.K_UP]:
            player_rect.y -= speed
        if pressed[pg.K_DOWN]:
            player_rect.y += speed
        if pressed[pg.K_LEFT]:
            player_rect.x -= speed
        if pressed[pg.K_RIGHT]:
            player_rect.x += speed
        # Clamp the rect to the dimensions of the screen_rect.
        player_rect.clamp_ip(screen_rect)

        screen.fill(BG_COLOR)
        screen.blit(image, player_rect)

        pg.display.flip()
        clock.tick(60)


if __name__ == '__main__':
    main()
    pg.quit()

Upvotes: 6

MooingRawr
MooingRawr

Reputation: 4991

What you are trying to do is called edge detection, as in detect if you are at an edge, in this case you want the edges to be the screen's edges. what you should do, is check if your x or y are at an edge, if so don't go any further.

if pressed[pygame.K_UP]: 
    if 0 < y-5 < 600:  #0 and 600 being the edges of your screen, you can use a variable to change it dynamically later one  
        y -= 5

Note this will only detect if the top left's square is going out of bounds, since x and y is the top and left coords for the rectangle, meaning the bottom right of the square will be able to still go out of bounds,

If you want to check the whole square, you will have to make adjustment calculations in the if statement, or base your x and y on the center (which you will still have to modify the if statement to something like below. (note I'm altering based on your current code for x and y being top left.

if pressed[pygame.K_UP]: 
    if (0 < y-5 < 600) or (0< y+60-5 <600)  #0 and 600 being the edges of your screen, you can use a variable to change it dynamically later one  
        y -= 5

This checks the other side of the square. Note for x you will check for the horizontal limits which in this case is 800. Also we are checking including the -5 because we want to see where we are going, not where we are at.

Upvotes: 0

LismUK
LismUK

Reputation: 119

Something like:

if pressed[pygame.K_UP]:
    if not (y > maxwidth or y < 0):
        y += 5

And so on for the others. the maxwidth looks like 600 in your code but I'd put it at the top of your code so you dont keep having to change it in different places.

Upvotes: 0

Ruso_x
Ruso_x

Reputation: 367

This should work

if pressed[pygame.K_UP] and y > 0: y -= 5
if pressed[pygame.K_DOWN] and y < 600 - 60: y += 5
if pressed[pygame.K_LEFT] and x > 0: x -= 5
if pressed[pygame.K_RIGHT] and x < 800 - 60: x += 5

Where 600 and 800 is the screen size and 60 the size of your rectangle

Upvotes: 2

Related Questions