Moving shapes

From TRCCompSci - AQA Computer Science
Jump to: navigation, search

Assuming you have the pygame template from one of the other pages. We can move objects by using variable to specify the X & Y coordinate. The example below does this (when the code is running, the loop will need to clear the screen, create the object and then draw it):

COLOR = (255, 0, 200)
BLACK = (0 , 0 , 0)
X=100 # X coordinate for object
Y=100 # Y coordinate for object

#game loop
while True:
    SCREEN.fill(BLACK) # Clear screen
    rect1 = pygame.Rect([X,Y,20,20]) # create shape
    pygame.draw.rect(SCREEN, COLOR, rect1, 1) # draw shape
    pygame.display.update() # update screen

    #respond to player input ans change X & Y coordinates for next draw
    for events in pygame.event.get(): #get all pygame events
        if events.type == pygame.KEYDOWN:
            if events.key == pygame.K_LEFT:
                X=X-10
            elif events.key == pygame.K_RIGHT:
                X=X+10
            elif events.key == pygame.K_UP:
                Y=Y-10
            elif events.key == pygame.K_DOWN:
                Y=Y+10
        if events.type

Alternatively

You can make a tuple (general python data type similar to vector or array etc) for the position and size. Your player input could then manipulate the values in the tuple:

pos = [100, 100, 20, 20] # X , Y , Width , Height
COLOR = (255, 0, 200)
BLACK = (0 , 0 , 0)

#game loop
while True:
    SCREEN.fill(BLACK)
    rect1 = pygame.Rect(pos) # use pos for the shape
    pygame.draw.rect(SCREEN, COLOR, rect1, 1)
    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 # pos[0] should be first item in the tuple 
            elif events.key == pygame.K_RIGHT:
               pos[0]=pos[0]+10 # pos[0] should be first item in the tuple
            elif events.key == pygame.K_UP:
                pos[1]=pos[1]-10  # pos[1] should be second item in the tuple
            elif events.key == pygame.K_DOWN:
                pos[1]=pos[1]+10 # pos[1] should be second item in the tuple