Place the code to draw object in to function
def drawBlock():
surface.blit(block,(block_x,block_y))
pygame.display.flip()
Add functionality in side while running:
loop,
use event.key
,
to use up, down, left, and right keys to affect block_x
and block_y
if event.key == K_DOWN: block_y += 10 if event.key == K_UP: block_y -= 10 if event.key == K_LEFT: block_x -= 10 if event.key == K_RIGHT: block_x += 10
Documentation is pygame.locals https://www.pygame.org/docs/ref/key.html#module-pygame.key
Place drawBlock()
at the bottom of while running:
loop. NOTICE block is being redraw, add
surface.fill((255,255,255))
to top of
drawBlock()
to clear screen
import pygame from pygame.locals import * def drawBlock(): surface.blit(block,(block_x,block_y)) pygame.display.flip() if __name__ == '__main__': pygame.init() surface = pygame.display.set_mode((500,400)) surface.fill((255,255,255)) block = pygame.image.load('images/block.jpg').convert() block_x = 100 block_y = 100 pygame.display.flip() running = True while running: for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_ESCAPE or event.key == K_q: running = False if event.key == K_DOWN: block_y += 10 if event.key == K_UP: block_y -= 10 if event.key == K_LEFT: block_x -= 10 if event.key == K_RIGHT: block_x += 10 if event.type == QUIT: running = False drawBlock()
Put surface.fill((255,255,255))
at top of drawBlock
def drawBlock(): surface.fill((255,255,255)) surface.blit(block,(block_x,block_y)) pygame.display.flip()
Now the block gets re-drawn everytime the surface is filled
import pygame from pygame.locals import * def drawBlock(): surface.fill((255,255,255)) surface.blit(block,(block_x,block_y)) pygame.display.flip() if __name__ == '__main__': pygame.init() surface = pygame.display.set_mode((500,400)) surface.fill((255,255,255)) block = pygame.image.load('images/block.jpg').convert() block_x = 100 block_y = 100 pygame.display.flip() running = True while running: for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_ESCAPE or event.key == K_q: running = False if event.key == K_DOWN: block_y += 10 if event.key == K_UP: block_y -= 10 if event.key == K_LEFT: block_x -= 10 if event.key == K_RIGHT: block_x += 10 if event.type == QUIT: running = False drawBlock()