Reputation: 11
I am not able to move the image on screen in pygame.
I have tried to move the image but the entire image is not moving but image just expands with KEYDOWN.
import sys
import pygame
def run_game():
"""An attempt to develop a simple game."""
pygame.init()
screen = pygame.display.set_mode((1200, 800))
pygame.display.set_caption("Rocket")
rocket_ship = pygame.image.load("images/alien_ship.bmp")
rec = rocket_ship.get_rect()
screen_rec = screen.get_rect()
rec.centerx = screen_rec.centerx
rec.bottom = screen_rec.bottom
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
rec.centerx += 5
elif event.key == pygame.K_LEFT:
rec.centerx -= 5
screen.blit(rocket_ship, rec)
pygame.display.flip()
run_game()
Upvotes: 1
Views: 26
Reputation: 14906
When the question says the "image is expanding" - I believe this is just a visual artefact of the previous image not being erased.
If the line:
screen.fill( 0,0,0 ) # paint the background black
is added at the beginning of the loop:
while True:
screen.fill( 0,0,0 ) # paint the background black
for event in pygame.event.get():
This remove the previously-painted alien from the screen.
A better way to handle this sort of thing is to use pyGame's built in sprites. This might seem like extra work right now, but will save you a lot of hassle in the future, as a lot of the "chores" involved with moving things around (and detecting collisions, etc.) are already handled by pygame's sprite code.
Upvotes: 1