#Bryan Medina
#6/22/2017
#squareCollision.py
#A look at how to verify if a collision has occured with squares.

#This will work almost identically to circleCollision.py

#Basic stuff that we always have to do
import pygame, sys
import random
from pygame.locals import *

def checkCollision(rectangle1, rectangle2):
    """A function that takes in two lists (each containing the properties of a square) and checking if the two squares have collided. 

    Returns
    -------
    collided: A boolean variable. Returns True if the squares have collided and False otherwise.
    """

    if rectangle2[0] > rectangle1[0] + rectangle1[4]: 
        return False
    if rectangle1[0] > rectangle2[0] + rectangle2[4]:
        return False
    if rectangle2[1] > rectangle1[1] + rectangle1[5]:
        return False
    if rectangle1[1] > rectangle2[1] + rectangle2[5]:
        return False
    
    return True

pygame.init()
DISPLAYSURF = pygame.display.set_mode((1000, 600))
pygame.display.set_caption("Rectangle Collision")

#variables to keep track of the width and height of the screen
width  = 1000
height = 600

clock = pygame.time.Clock()

colors = [pygame.Color(0, 128, 0), pygame.Color(255, 0, 0), pygame.Color(192, 192, 192), pygame.Color(128, 0, 128), pygame.Color(0  ,  0,255)]


#We're going to need two squares.

#We're going to store of all square properties in a list of lists.
#Each list is going to contain an x position, y position, x speed, y speed, width, height and a color
#(in that order).

square1 = [600 , 275, 0, 0, 50, 50, pygame.Color(255,  0,  0)]
square2 = [300 , 275, 0, 0, 50, 50, pygame.Color(0  ,  0,255)]

while True:

    # Event loop for each iteration
    for event in pygame.event.get():

        # To handle exiting the game.     
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

        #Handle key being pressed
        if event.type == KEYDOWN:
            if event.key == K_DOWN:
                square1[3] = 20
            if event.key == K_UP:
                square1[3] = -20
            if event.key == K_LEFT:
                square1[2] = -20
            if event.key == K_RIGHT:
                square1[2] = 20

        #Handle key being released
        if event.type == KEYUP:
            square1[3] = 0
            square1[2] = 0

                
    square1[1] += square1[3]
    square1[0] += square1[2]

    if(checkCollision(square1, square2) == True):
        square1[6] = colors[random.randint(0, 4)]
        square2[6] = colors[random.randint(0, 4)]
    
    # Display everything for this iteration.
    DISPLAYSURF.fill(pygame.Color(0, 0, 0))
    pygame.draw.rect(DISPLAYSURF, square1[6], (square1[0], square1[1], square1[4], square1[5]), 0)
    pygame.draw.rect(DISPLAYSURF, square2[6], (square2[0], square2[1], square2[4], square2[5]), 0)

    
    #Change the framerate
    clock.tick(100)
    
    pygame.display.update()
