Move a square, and stop at a block
move_square_stop_at_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() xprevious = x yprevious = y 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 me = pygame.Rect(x, y, 60, 60) if me.colliderect(block): x = xprevious y = yprevious me = pygame.Rect(x, y, 60, 60) screen.fill((255, 255, 255)) pygame.draw.rect(screen, (0,0,0), me) pygame.draw.rect(screen, (255,0,0), block) pygame.display.flip() clock.tick(60) pygame.quit()