#usr/bin/python

######## LICENSE ########
##This is a template file that shows the basic layout for most games. It
##is a good starting point when beginning a game. I have tried to 
##document the code as clearly as possible. This template was created
##by Simon Baumgardt-Wellander for use by the Olympia High School Game
##Developers Club, but it is released under the BSD license.


######## IMPORTS ########
##This is where you import the modules your game requires. These are
##some of the most common modules for games to use, though they often
##use many others, including custom written ones.

#pygame is the main library for game development that allows you to
#have graphics and sounds and other great things
import pygame
#random allows you to do all sorts of cool things with random numbers,
#from generating random integers, to normal distributions, to shuffling
#lists and choosing samples from them
import random
#math allows you to do more complex math (though not technically
#complex, no imaginary numbers) such as trigenometry, factorials
#and logarithms.
import math
#os allows you to interface with the operating system, though all I've
#ever used it for is get paths to files since unix uses '/' and windows
#uses '\'
import os

#allows use of pygame constants for ease of programming
from pygame.locals import *


######## CONSTANTS ########
##These are variables you will use throughout your game that you should
##not change. It is good practice to set your constants at the top of
##the file and use them rather than have numbers scattered throughout
##your code. Colors can go here too, though when there are more than a
##few, it's usually good practice to put them in a separate document

FRAMERATE = 60

#Useful mathematecal constants
PI_OVER_TWO = math.pi*0.5
TWO_PI = math.pi*2

#usually better to put colors in another document
COLOR_BACKGROUND = (80,80,80)
COLOR_TEXT = (200,200,200)


######## CLASSES ########
#These are the 'blueprints' for objects in the game. A standard thing
#looks something like this:

class Thing():
	"""Any object in the game."""
	def __init__(self, (x,y)):
		"""This is called automatically when you make an instance of the
		object. It is where you initialize variables and possibly add it
		to the list of game objects."""
		self.x,self.y = x,y
		gameObjects.append(self)
	def update(self):
		"""This you call every frame. This is where you do most of the
		things that will make the object do stuff."""
		pass
	def draw(self):
		"""This you usually call at the end of every frame. It draws the
		sprite of the object onto the screen."""
		pass
	def remove(self):
		"""You call this when you want to remove the instance from the
		game. It usually removes the instance from the game object list
		as well as possibly creating an 'on death' animation or sound."""
		gameObjects.remove(self)


######## FUNCTIONS ########
##These are global functions that can do all sorts of things for the
##game from loading resources to saving the game to playing sounds to
##drawing the background.

def load_image(name, alpha = 'auto'):
	"""Loads an image from the resources/images directory underneath the
	game's working directory. Returns a pygame surface. If the image
	cannot be loaded, raises an error. Optional parameter 'alpha' can be
	set to True, False or 'auto' to determine whether to load the
	image's	alpha channel."""
	fullname = os.path.join('resources','images', name)
	try:
		image = pygame.image.load(fullname)
		if (alpha == False) or (image.get_alpha() is None and alpha != True):
			image = image.convert()
		else:
			image = image.convert_alpha()
	except pygame.error, message:
		print 'Cannot load image:', fullname
		raise SystemExit, message
	return image
def load_sound(name):
	"""Loads a sound from the resources/sounds directory underneath the
	game's working directory. Returns a pygame sound object. If the
	sound cannot be loaded, raises an error."""
	if not pygame.mixer: #Test for sound capabilities
		print "pygame.mixer Not Functioning"
		exit()
	fullname = os.path.join('resources','sounds', name)
	try:
		sound = pygame.mixer.Sound(fullname)
	except pygame.error:
		print ('Cannot load sound:', fullname)
		raise SystemExit, message
	return sound
def draw_background():
	"""Call this to draw the background on the screen."""
	screen.fill((COLOR_BACKGROUND))
def draw_text(targetSurface, text, (x,y) = ('c','c'), font=None, color = (255,255,255)):
	"""Draws text on the targetSurface at position (x,y) in font and
	color. Defaults to black. Substitute "c" for a value to center on
	that axis."""
	if "c" not in (x,y):
		text = font.render(text, True, color)
		targetSurface.blit(text, (x,y))
		return
	width,height = font.size(text)
	surfaceWidth, surfaceHeight = targetSurface.get_size()
	if x == "c":
		x = surfaceWidth/2-width/2
	if y == "c":
		y = surfaceHeight/2-height/2
	text = font.render(text, True, color)
	targetSurface.blit(text, (x,y))


######## INITIALISATIONS ########
##This is the code that is run once at the beginning of your game as it
##loads. This usually involves loading images as well as preparing
##pygame for use.

#initialises pygame
pygame.init()
#creates a window to draw in. The function's first argument is size;
#(0,0) denotes to use the current monitor resolution. FULLSCREEN says
#to make the window fullscreen 
screen = pygame.display.set_mode((0,0), FULLSCREEN)
#the clock is used to limit the framerate
clock = pygame.time.Clock()

#Now we make variables for things we will use later
#holds the position of the mouse
mousePosition = mousex,mousey = 0,0
#Holds the state of the mouse buttons as True or False
mouseButtons = [False,False,False,False,False,False,False]
#Holds the state of the keys buttons as True or False
keys = []
#adds 512 keys to the list because it seems like a good number
for i in range(512):
	keys.append(False)
#this is a list of all objects in the game to keep track of. When they
#are removed from this list, they will not be updated or drawn, and will
#be destroyed when the garbage collector gets around to it
gameObjects = []


######## MAIN LOOP ########
#This is the main loop of your game, which calls all the update and
#drawing functions in the right order, as well as handle user input

while True:
	
	#Hanle user input.
	#Update mouse position
	mousePosition = mousex,mousey = pygame.mouse.get_pos()
	#This sets the states of your arrays for keys and mouse buttons
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			exit()
		elif event.type == pygame.KEYDOWN:
			keys[event.key] = True
			if event.key == K_ESCAPE:
				exit()
		elif event.type == pygame.KEYUP:
			keys[event.key] = False
		elif event.type == pygame.MOUSEBUTTONDOWN:
			mouseButtons[event.button] = True
		elif event.type == pygame.MOUSEBUTTONUP:
			mouseButtons[event.button] = False
	
	#draw background
	draw_background()
	#update all game objects
	for item in gameObjects:
		item.update()
	
	#draw all game objects
	for item in gameObjects:
		item.draw()
		
	#update the screen to show everything new that's been updated
	pygame.display.flip()

	#limit the framerate to what we defined in the CONSTANTS section
	clock.tick(FRAMERATE)
