# Python 2.7.7 Code
# Pygame 1.9.1 (for Python 2.7.7)
# Jonathan Frech 25th of July, 2015

# importing needed modules
import pygame, sys, time, math, os, random

""" CLASSES """
# dummy class for global variables
class dummy():
	pass

# entity class
class entity():
	def __init__(self, _pos):
		self.pos = _pos
		self.speed = [random.randint(-10, 10), random.randint(-10, 10)]
		self.life = 0
		self.dead = False
		
		self.color = [50, 100, 150]
		self.size = 15
	
	def render(self, _surface):
		pygame.draw.circle(_surface, self.color, self.pos, self.size)
	
	# tick (move, change color, change speed and die)
	def tick(self):
		self.life += 1
		for _ in range(0, 2):
			self.pos[_] += self.speed[_]
			if self.pos[_] < 0:
				self.pos[_] = 0
				self.speed[_] *= -1
			if self.pos[_] > main.SIZE[_]:
				self.pos[_] = main.SIZE[_]
				self.speed[_] *= -1
		
		for _ in range(0, 3):
			self.color[_] -= 1
			if self.color[_] < 0:
				self.color[_] = 0
		
		if self.color == [0, 0, 0]:
			self.dead = True

""" FUNCTIONS """
# gets the mouse position
def getMousePos():
	p = pygame.mouse.get_pos()
	return [p[0], p[1]]

# quits the program
def quit():
	sys.exit()

""" TICK; RENDER """
# tick function
def tick():
	# handle events
	for event in pygame.event.get():
		# quit
		if event.type == pygame.QUIT:
				quit()
		
		# keydown
		if event.type == pygame.KEYDOWN:
			if event.key == pygame.K_SPACE:
				main.ACTIVE = not main.ACTIVE
	
	if main.ACTIVE:
		if len(main.ENTITIES) < 300:
			main.ENTITIES.append(entity(getMousePos()))
		
		for _ in main.ENTITIES:
			_.tick()
			if _.dead:
				main.ENTITIES.remove(_)

# render function
def render():
	# fill
	main.SURF.fill(main.COLOR)
	
	for _ in main.ENTITIES:
		_.render(main.SURF)
	
	# blit and flip
	main.SCREEN.blit(main.SURF, [0, 0])
	pygame.display.flip()

""" INIT """
# initialize program
def init():
	main.WIDTH, main.HEIGHT = 1080, 720
	main.SIZE = [main.WIDTH, main.HEIGHT]
	main.SCREEN = pygame.display.set_mode(main.SIZE)
	main.SURF = pygame.Surface(main.SIZE)
	
	main.CAPTION = "Bobble Throw"
	main.COLOR = (0, 0, 0)
	main.TICKS = 0
	
	main.ENTITIES = []
	main.ACTIVE = True
	
	# functions
	pygame.display.set_caption(main.CAPTION)

""" RUN """
# run function (uses tick() and render())
def run():
	ticksPerSecond = 60
	lastTime = time.time() * 1000000000
	nsPerTick =  1000000000.0 / float(ticksPerSecond)
	
	ticks = 0
	frames = 0
	
	lastTimer = time.time() * 1000
	delta = 0.0
	
	while True:
		now = time.time() * 1000000000
		delta += float(now - lastTime) / float(nsPerTick)
		lastTime = now
		shouldRender = False
				
		while delta >= 1:
			ticks += 1
			main.TICKS += 1
			tick()
			delta -= 1
			shouldRender = True
		
		if shouldRender:
			frames += 1
			render()
		
		if time.time() * 1000 - lastTimer >= 1000:
			lastTimer += 1000
			
			# debug
			# print("Frames: " + str(frames) + ", ticks: " + str(ticks))
			
			frames = 0
			ticks = 0

# main variable
main = dummy()
init()

# start program
run()
