Pygame - Moving an object based on key pressed

# Moving an object based on keypress


import sys,pygame


pygame.init()

screen = pygame.display.set_mode((500, 500))

pygame.display.set_caption("Moving object")

  

# Moving object starting co-ordinates and size

x = 200

y = 200


width = 20

height = 20

  

# Moving speed

step = 5

  

# infinite loop 

while 1:

pygame.time.delay(10)

for event in pygame.event.get():

if event.type == pygame.QUIT:

sys.exit()


# Get the keys pressed 

keys = pygame.key.get_pressed()

      

    # Left arrow key - decrement in x axis

if keys[pygame.K_LEFT]and x>0:

x-=step

    # Right arrow key - increment in x axis

if keys[pygame.K_RIGHT] and x<500-width:

x += step

         

    # Up arrow key - decrement in y axis

if keys[pygame.K_UP] and y>0:

y -= step

          

    # Down arrow key - increment in y axis

if keys[pygame.K_DOWN] and y<500-height:

y += step

        

    # Set screen background and Place moving object on screen 

screen.fill((255, 255, 255))

pygame.draw.rect(screen, (255, 0, 0), (x, y, width, height))

      

    # Display movement

pygame.display.update() 

  

pygame.quit()

No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu