1

So I have a function that keeps the sprite from moving off screen which is:`

def move_extent(self, x, y):
    if self.rect.right > 700:
      self.rect.right = 700
    elif self.rect.left < 0:
      self.rect.left = 0
    elif self.rect.y < 275:
      self.rect.y = 275
    elif self.rect.y > 275:
      self.rect.y = 275`

And it keeps the sprite from moving past the x coords, and for the most part, the y coords. But if the sprite is on either the far left or far right (0 or 700 x), it will still go up or down.

Heres the main game loop:

while not done:

    for event in pygame.event.get():
      if event.type == pygame.QUIT:
        done = True

    keys = pygame.key.get_pressed()
    if keys[pygame.K_a]:
      protag.moveLeft(3)
    if keys[pygame.K_d]:
      protag.moveRight(3)
    if keys[pygame.K_w]:
      protag.moveUp(3)
    if keys[pygame.K_s]:
      protag.moveDown(3)


    all_sprites_list.update()

    screen.blit(background, (0, 0))

    all_sprites_list.draw(screen)
    move_extent(protag, x_coord, y_coord)

    pygame.display.flip()

    clock.tick(60)

pygame.quit()
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
ajjanna12
  • 25
  • 3

1 Answers1

1

Almost :) change your tests to:

def move_extent(self, x, y):  # x and y are never used?
    if self.rect.right > 700:
        self.rect.right = 700

    if self.rect.left < 0:
        self.rect.left = 0

    if self.rect.y < 275:   # why y twice? this will limit y to be 275
        self.rect.y = 275   # and x is never checked ...

    if self.rect.y > 275:   # why y twice? this will limit y to be 275
        self.rect.y = 275`

Currently your earlier if is used and all others test wont be tested anymore.

You could shorten this to:

def move_extent(self, x, y): 
    self.rect.right = min(700,self.rect.right) # take whatever is lower
    self.rect.left  = max(  0, self.rect.left) # take whatever is higher 
    self.rect.y = 275                          # fix y at 275

https://docs.python.org/3/library/functions.html#max https://docs.python.org/3/library/functions.html#min

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69