External Exam Download Resources Web Applications Games Recycle Bin

Move a square

square_move.py

import pygame
pygame.init()
screen = pygame.display.set_mode((400, 300))
done = False
clock = pygame.time.Clock()

x,y = 170,120 #start square in middle centre

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
            
    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_UP]: y = y - 3
    if pressed[pygame.K_DOWN]: y = y + 3
    if pressed[pygame.K_LEFT]: x = x - 3
    if pressed[pygame.K_RIGHT]: x = x + 3
        
    screen.fill((255, 255, 255)) #white background
    pygame.draw.rect(screen, (0,0,0), pygame.Rect(x, y, 60, 60))
    pygame.display.flip()
    clock.tick(60)
    
pygame.quit()