Skip to content Skip to sidebar Skip to footer

How To Change A Sprite On The Screen After Pressing A Key In Pygame

I'm new to Pygame, and still learning Python. I'm using Python 3.4. I followed this amazing game creation tutorial: http://pythonprogramming.net/pygame-python-3-part-1-intro/. Aft

Solution 1:

At each frame, you display the image in the global variable called carImp in this function:

defcar(x, y):
    gameDisplay.blit(carImp, (x, y))

SO, what you have to do is to change the contents of this variable to point to the desired image before the display. You should first read all the images for your car – you can read them all into a dictionary to avoid polluting your namespace (even more than it is polluted) with a variable name for each sprite:

So, in the beginning, some code like:

car_image_names = ["racecar", "move_right", "move_left"]
car_sprites = dict(((img_name, pygame.image.load(img_name + ".png"))
                        for img_name in car_image_names)
carImp = car_sprites["racecar"]

(Here I've used a shortcut called "generator expression" to avoid having to write a "pygame.image.load" for each car image.)

And then, in your main loop, after you've read the keyboard, and detected whether the car is moving right or left (which you reflect in x_change) – just change carImp accordingly:

if x_change == 0:
    carImp = car_sprites["racecar"]
elif x_change > 0:
    carImp = car_sprites["move_right"]
elif x_change < 0:
    carImp = car_sprites["move_left"]

Post a Comment for "How To Change A Sprite On The Screen After Pressing A Key In Pygame"