# Arup Guha
# 7/15/2015
# "Rain" simulation - uses lists

import random
import math
import time
import pygame, sys
from pygame.locals import *
from TokenFile import token

# Useful Constants
SCREEN_W = 1000
SCREEN_H = 600
DY = 5
RADIUS = 10
BLACK = pygame.Color(0,0,0)
BLUE = pygame.Color(0,0,255)

# This function handles moving each item listed in items.
def move(items):
    for item in items:
        item.move()

# This function removes all items that will never be visible again.
def removeUseless(items):
    for item in items:
        if item.y > SCREEN_H:
            items.remove(item)

# Returns a new random color
def makeRandomColor():
    r = random.randint(0, 255)
    g = random.randint(0, 255)
    b = random.randint(0, 255)
    return pygame.Color(r,g,b)

def main():

    # Basic setup.
    pygame.init()
    DISPLAYSURF = pygame.display.set_mode((SCREEN_W, SCREEN_H))
    pygame.display.set_caption("Let it rain!")
    clock = pygame.time.Clock()

    # Store all raindrops here.
    rain = []

    frame = 0

    # Game loop.
    while True:
        
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()    

        # Calculate number of new drops to add this iteration, then randomly
        # generate that many unique values.
        numNewRain = random.randint(1, 3)

        # Lots of rain for 3 frames out of every 100.
        if frame%100 >= 70 and frame%100 <= 89:
            numNewRain = 50
        
        xvals = set()
        while len(xvals) < numNewRain:
            x = random.randint(1, SCREEN_W)
            xvals.add(x)
        
        # Add each if these items into the list rain.
        for val in xvals:
            rain.append(token(val,0,1,DY,RADIUS,makeRandomColor()))
         
        DISPLAYSURF.fill((255,255,255))

        # Draw each raindrop individually.
        for item in rain:
            item.draw(DISPLAYSURF)

        pygame.display.update()

        # Go through each item.
        for item in rain:

            # We speed up once every 5 frames.
            if frame%5 == 0:
                item.changeVelocity(0, 1)

            # We change colors once every 15 frames.
            if frame%15 == 0:
                item.changeColor(makeRandomColor())

        # Move the drops for the next iteration and remove useless ones.
        move(rain)
        removeUseless(rain)
        frame += 1
        clock.tick(30)

# Run it.
main()
