Difference between revisions of "Moving shapes"

From TRCCompSci - AQA Computer Science
Jump to: navigation, search
Line 1: Line 1:
 
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):
 
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):
  
<syntaxhighlight lang=python>
 
 
<syntaxhighlight lang=python>
 
<syntaxhighlight lang=python>
 
COLOR = (255, 0, 200)
 
COLOR = (255, 0, 200)
Line 27: Line 26:
 
                 Y=Y+10
 
                 Y=Y+10
 
         if events.type
 
         if events.type
</syntaxhightlight>
+
</syntaxhighlight>

Revision as of 08:51, 28 February 2018

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