Drawing images

From TRCCompSci - AQA Computer Science
Revision as of 13:42, 1 March 2018 by Admin (talk | contribs) (Created page with "==Method One== One method is to simply load the image and then draw it to the screen in a given position. When you alter the position and redraw the screen the image will move...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Method One

One method is to simply load the image and then draw it to the screen in a given position. When you alter the position and redraw the screen the image will move:

pos = [100,100] # starting position of player image
player = pygame.image.load(os.path.join("hero.png")).convert(); # load in player image
player = pygame.transform.scale(player, (20, 30)) # resize player image

#game loop
while True:
    SCREEN.fill(BLACK)
    SCREEN.blit(player,pos) # blit will draw the image to the screen
    pygame.display.update()
    for events in pygame.event.get(): #get all pygame events
        if events.type == pygame.KEYDOWN:
            if events.key == pygame.K_LEFT:
                pos[0]=pos[0]-10
            elif events.key == pygame.K_RIGHT:
               pos[0]=pos[0]+10
            elif events.key == pygame.K_UP:
                pos[1]=pos[1]-10
            elif events.key == pygame.K_DOWN:
                pos[1]=pos[1]+10

Method 2

You could alternatively create a surface, then load the image onto the surface. The user input can move the surface instead of the image:

pos = [100,100] # position for image
playerSurface = pygame.Surface((20,30)) # surface to draw image onto
player = pygame.image.load(os.path.join("hero.png")).convert(); # load image
player = pygame.transform.scale(player, (20, 30)) # resize image

#game loop
while True:
    SCREEN.fill(BLACK)
    playerSurface.blit(player, (0,0)) # draw player on the surface at position 0,0
    SCREEN.blit(playerSurface,pos) # draw the surface onto the screen at the position of pos
    pygame.display.update()
    for events in pygame.event.get(): #get all pygame events
        if events.type == pygame.KEYDOWN:
            if events.key == pygame.K_LEFT:
                pos[0]=pos[0]-10
            elif events.key == pygame.K_RIGHT:
               pos[0]=pos[0]+10
            elif events.key == pygame.K_UP:
                pos[1]=pos[1]-10
            elif events.key == pygame.K_DOWN:
                pos[1]=pos[1]+10