Main program:
player = Player("player.png",[10,650])
players = pygame.sprite.Group()
players.add(player)
while True:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_RIGHT:
player.goright()
if event.key == K_LEFT:
player.goleft()
if event.type == KEYUP:
if event.key == K_RIGHT:
player.cangoright = False
if event.key == K_LEFT:
player.cangoleft = False
players.update()
players.draw(SCREEN)
pygame.display.update()
clock.tick(FPS)
The relevant sprite’s functions:
def update(self):
if self.cangoright:
self.rect.left += self.speed
if self.cangoleft:
self.rect.left -= self.speed
def goright(self):
if self.rect.right <= 1024:
self.cangoright = True
else:
self.cangoright = False
def goleft(self):
if self.rect.left >= 0:
self.cangoleft = True
else:
self.cangoleft = False
The problem is that the “cangoright” and “cangoleft” flags don’t seem to be working properly. When the sprite has surpassed the edges of the screen (0 on the left and 1024 on the right), the flags should be set to false, and thus the ifs in the update function should return false, but this doesn’t happen.
I believe part of the problem is that you’re only updating
leftinself.rect. Try updating bothleftandrightinstead, and see if that changes things.More importantly, this code is a bit hard to read, and too complex what you’re trying to do. You might be better served by checking the bounds of the screen in your
updatefunction instead of in your key event handler. In reality this is part of the physics of your game, so it should probably be hung off of there.In other words, use the event loop to set flags which express the intention of the player to the
updatefunction. Use theupdatefunction to apply the rules of the game (physics, etc) to the game state based on the flags set by the event loop.Maybe something like this?