One of the problems with our prior pygame animation is that once the red square goes to far to the left, we don’t do anything. It just seems to be gone forever !
What we want to write is the python code that says, “Hey if the image goes all the way to left, off of the screen, then set its x coordinate (ie imageX) back to the total right!) As shown here;
The two highlighted lines of code below do exactly that. We discuss those 2 lines at length below.
The get_rect() method is a handy method that pygame supplies us . It allows us to figure out.
What we want to do is set the imageX value back to width (350) as soon as the image’s x value is at – get_rect().width
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
import pygame pygame.init() width=350; height=400 screen = pygame.display.set_mode( ( width, height) ) redSquare = pygame.image.load ("images/red-square.png").convert() fpsClock = pygame.time.Clock() imageX= 200; # x coordnate of image imageY= 30; # y coordinate of image running = True black = ( 0 , 0 , 0) while (running): # loop listeneint for end of game imageX -= 20 ; if imageX <= -redSquare.get_rect ().width : imageX= 350 screen.fill(black) # clear screen screen.blit(redSquare , (imageX, imageY) ) # paint to screen for event in pygame.event.get(): if event.type == pygame.QUIT: running = False pygame.display.update() fpsClock.tick(30) #loop over, quite pygame pygame.quit() |