#copyright Drakonen

#usage: python thisfile.py
#depends on pygame

import sys, pygame, time, random

from math import floor

colorchangespeed = 60 

planes = []

#black_square_that_is_the_size_of_the_screen = pygame.Surface(screen.get_size())
#black_square_that_is_the_size_of_the_screen.fill((0, 0, 0))
#screen.blit(black_square_that_is_the_size_of_the_screen, (0, 0))
#pygame.display.flip()

def random_color():
    return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))


def step_to_color(color, targetcolor):
    color = list(color)
    difference = (targetcolor[0] - color[0], targetcolor[1] - color[1], targetcolor[2] - color[2])


    color = [color[0] + (difference[0] / colorchangespeed),
             color[1] + (difference[1] / colorchangespeed),
             color[2] + (difference[2] / colorchangespeed)]

    return color



class Plane:

    def __init__(self, planepos, winpos=None, color=None):
        self.counter = 0
        self.color = random_color()
        self.newcolor = random_color()


        self.planepos = planepos
        self.winpos = winpos

        if color:
            self.color = color
        else:
            self.color = random_color()

        if winpos:
            self.winpos = winpos
        else:
            self.winpos = self.calcWinPos()



    def calcWinPos(self):
        """determine window positions for plane"""
        colwidth = floor(width / float(planecols))
        colstart = floor((width / float(planecols)) * self.planepos[1])

        rowheight = floor(width / float(planerows))
        rowstart = floor((height / float(planerows)) * self.planepos[0])

        self.winpos = (int(colstart), int(rowstart), int(colwidth), int(rowheight))
        print self.winpos
        return self.winpos


    def update(self):
        #print "updating", self.planepos, self.winpos, self.color, self.newcolor
        if self.counter >= colorchangespeed:
            self.counter = 0
            self.newcolor = random_color()

        self.counter = self.counter + 1

        self.color = step_to_color(self.color, self.newcolor)
        pygame.draw.rect(screen, self.color, self.winpos)
        


def create_planes(planerows, planecols):
    for i in range(planerows):
        for j in range(planecols):
            print i, j
            planes.append(Plane((i,j)))


if __name__ == '__main__':
    pygame.init()

    size = width, height = 800, 600
    screen = pygame.display.set_mode(size, pygame.FULLSCREEN)

    color = (0, 0, 0)
    planes = []
    planerows = planecols = 4
    create_planes(planerows, planecols)

    while 1:
        for i in planes:
            i.update()
        pygame.display.flip()
        time.sleep(1/30.0)
        for event in pygame.event.get():
            if event.type in (pygame.QUIT, pygame.KEYDOWN):
                sys.exit()

