import pygame, sys from time import * from pygame.locals import * # Sides cannot go over each other (Minnimum square height and width) # Square cannot exit screen pygame.init() P = pygame.display.set_mode((1500, 900)) P.fill((255, 255, 255)) pygame.display.update() x = 40 # x coordinate y = 40 # Y Coordinate a = 40 # Up Expand b = 40 # Down Expand c = 40 # Left Expand d = 40 # Right Expand shape1 = pygame.Rect(544, 544, 56, 56) def square(): global line1, line2, line3, line4 P.fill((255, 255, 255)) line1 = pygame.draw.line(P, (0, 0, 0), (x - c, y - a), (x + d, y - a), width=1) # Top line2 = pygame.draw.line(P, (0, 0, 0), (x - c, y - a), (x - c, y + b), width=1) # Left line3 = pygame.draw.line(P, (0, 0, 0), (x - c, y + b), (x + d, y + b), width=1) # Bottom line4 = pygame.draw.line(P, (0, 0, 0), (x + d, y - a), (x + d, y + b), width=1) # Right def move(AB=0, CD=0, X=0, Y=0): global a, b, c, d, x, y a += AB b += AB c += CD d += CD x -= X y -= Y def check(): Collided = False global y1 global y2 y1 = 0 y2 = 0 line1_rect = pygame.Rect(x - c, y - a, c + d, a+b) for ypos in range (a+b): if pygame.Rect.collidepoint(x-c, ypos): y1 = ypos Collided = True if not pygame.Rect.collidepoint(x-c, ypos) and Collided: y2 = ypos return return not line1_rect.colliderect(shape1) while True: for event in pygame.event.get(): PressedKey = pygame.key.get_pressed() if event.type == QUIT: pygame.quit() sys.exit() if PressedKey[K_w] and 1<=y-4-a: move(4, 0, 0, 4) if not check(): move(-4, 0, 0, -4) if PressedKey[K_s] and y+4+b<=900: move(4, 0, 0, -4) if not check(): move(-4, 0, 0, 4) if PressedKey[K_a] and 1<=x-4-c: move(0, 4, 4) if not check(): move(0, -4, -4) if PressedKey[K_d] and x+4+d<=1500: move(0, 4, -4) if not check(): move(0, -4, 4) if PressedKey[K_g] and 80<=(y+b)-(y-a+4): move(-4, 0, 0, -4) if PressedKey[K_t] and 80<=(y+b-4)-(y-a): move(-4, 0, 0, 4) if PressedKey[K_h] and 80<=(x+d-4)-(x-c): move(0, -4, -4) if PressedKey[K_f] and 80<=(x+d)-(x-c+4): move(0, -4, 4) if event.type == pygame.KEYUP: if event.key == pygame.K_r: # Loop where first the box is centred, then the a, b, c, d values are adjusted accordingly, before the values of each variable goes progressively closer to zero, of which the speed depends on the distance. square() ydrift = (a + b) / 2 # Distance from upper most and lower most points of the original box xdrift = (c + d) / 2 # Distance from left most and right most points of the original box a = ydrift b = ydrift c = xdrift d = xdrift shrinkx = (xdrift-40) / 16 shrinky = (ydrift-40) / 16 for number in range(16): move(-shrinky) move(0,-shrinkx) sleep(0.02) square() pygame.draw.rect(P, (255, 0, 0), shape1) pygame.display.update() square() pygame.draw.rect(P, (255, 0, 0), shape1) centrex = ((x + 10 + c) + (x + 100 + d)) / 2 - 40 centrey = ((y + 10 + a) + (y + 100 + b)) / 2 - 40 pygame.display.update()