External Exam Download Resources Web Applications Games Recycle Bin

Move a square, and touch a block

square_move_touch_block.py

import pygame
pygame.init()
screen = pygame.display.set_mode((400, 300))
done = False
clock = pygame.time.Clock()
x,y = 170,120
block = pygame.Rect(0,0,60,60)
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))
    me = pygame.Rect(x, y, 60, 60)
    pygame.draw.rect(screen, (0,0,0), me)
    pygame.draw.rect(screen, (255,0,0), block)
    if me.colliderect(block): print("ouch") #place_meeting() in gamemaker
    pygame.display.flip()
    clock.tick(60)
    
pygame.quit()