0

I am working on a pygame and I would like the controlled character to flip between two images whenever it is moving to simulate walking. I've been working on a solution for a few hours now and can not think of anything. Here's some code I have tried.

'''Update the visual screen.'''
screen.fill(settings.bg_color)
player.blitme()

player_imagea = pygame.image.load('images/player_imagea.bmp') 
player_imageb = pygame.image.load('images/player_imageb.bmp') 

if player.moving_right and player.image == player_imagea:
    player.image = pygame.image.load('images/player_imageb.bmp')
elif player.moving_right and player.image == player_imageb:
    player.image = pygame.image.load('images/player_imagea.bmp')

#Draw the most recent screen
pygame.display.flip()

Doing this results in nothing happening aside from the movement I have already programmed. I have been able to get the image to switch upon the first keypress but nothing beyond that.

martineau
  • 119,623
  • 25
  • 170
  • 301
Nerdtendo
  • 11
  • 3
  • Why don't you set the player image to the images you've loaded, but instead load in completely new images? I'm not sure but I don't think checking equality between two different images work. If you would set the player image to `player_imagea` or `player_imageb` you could instead check for identity. Also, where in the code is this? Loading in images in the main loop is generally a bad idea, you'd rather want to load all images into a dict or list at the beginning of the program. – Ted Klein Bergman Feb 02 '17 at 18:49
  • I'll try that! This code is in a different file that handles all game functions so I should be fine. – Nerdtendo Feb 02 '17 at 18:51
  • It almost works but it ignores the elif block so it flips to imageb but not back to imagea until player.moving_right = False. Is there a way to execute two commands in the same block but leave delay between them? – Nerdtendo Feb 02 '17 at 19:01
  • If you call this code from the main loop (either if it's in the same file or in another file) you're loading in the images every frame, which can be very though for your computer depending on the amount of images and the size. Also, use [convert](http://stackoverflow.com/documentation/pygame/7079/drawing-on-the-screen/23787/surfaces#t=201702021916530826927) on your images after you've loaded in them. Now, your main problem: the problem must lie somewhere else in your code. According to your example it's impossible for the player image to change if `player.moving_right` is False. – Ted Klein Bergman Feb 02 '17 at 19:19
  • maybe you should do this in two steps - `if player.moving_right:` and later `if player.image == player_imagea: ... else: ...`. But you could use list and `if frame_number == 0: frame_number = 1 else: frame_number = 0` – furas Feb 02 '17 at 22:06
  • Check out [this](http://stackoverflow.com/a/42013186/6486738) answer for a complete example. – Ted Klein Bergman Feb 02 '17 at 22:08

0 Answers0