Python | Pygame collision

/ 20 Aug 2013 /
This is what I did, from a tutorial :'(



import pygame

pygame.init()

size = (1400, 800)
window = pygame.display.set_mode(size)
pygame.display.set_caption('Window')

white = (255, 255, 255)
black = (0,0,0)
red = (255,25,25)

moveX, moveY = 0, 0

clock = pygame.time.Clock()


def detect(x1, y1, w1, h1, x2, y2, w2, h2):
    if x2 + w2 >= x1 >= x2 and y2 + h2 >= y1 >= y2:
        return True

    elif x2 + w2 >= x1 + w1 >= x2 and y2 + h2 >= y1 >= y2:
        return True

    elif x2 + w2 >= x1 >= x2 and y2 + h2 >= y1 + h1 >= y2:
        return True

    elif x2 + w2 >= x1 + w1 >= x2 and y2 + h2 >= y1 + h1 >= y2:
        return True
    else:
        return False

class Sprite:
    
    def __init__(self,x,y):
        self.x = x
        self.y = y
        self.width = 50
        self.height = 50

    def render(self, coll):

        if coll:
            pygame.draw.rect(window, red, (self.x, self.y, self.width, self.height))
        elif coll is False:
            pygame.draw.rect(window, black, (self.x, self.y, self.width, self.height))
        

Sprite1 = Sprite(100,150)
Sprite2 = Sprite(200, 250)

run = True

while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                moveX = -5
            if event.key == pygame.K_RIGHT:
                moveX = 5
            if event.key == pygame.K_UP:
                moveY = -5
            if event.key == pygame.K_DOWN:
                moveY = 5
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                moveX = 0
            if event.key == pygame.K_RIGHT:
                moveX = 0
            if event.key == pygame.K_UP:
                moveY = 0
            if event.key == pygame.K_DOWN:
                moveY = 0

    window.fill(white)

    Sprite1.x+=moveX
    Sprite1.y+=moveY

    coll = detect(Sprite1.x, Sprite1.y, Sprite1.width, Sprite1.height, Sprite2.x, Sprite2.y, Sprite2.width, Sprite2.height)
    
    Sprite1.render(coll)
    Sprite2.render(False)
    
    clock.tick(120)
    pygame.display.flip()
pygame.quit()
 
Copyright © 2010 M(ath)+me, All rights reserved