# All Game code Copyright (C) 2008-2009 Charlie Dog Games
# Changes for GNU/Linux port Copyright (C) 2008-2009 W.P. van Paassen

# This file is part of Atomic Worm.

# Atomic Worm is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# Atomic Worm is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with Atomic Worm.  If not, see <http://www.gnu.org/licenses/>.

currentVersion = 34
showNonFreeLogos = 1
showOberon = 0
showAllLogo = 1 #set true for charlie dog logo
showPubLogo = 1
demoGame = 0
testCutScene = -1
renderDetailLevel = 2
localAppData = None
startingLevel = 0
startingLockLevel = 5
startLevel= 0
globalNumber = 0
#FIXME
cheatsActive = 0

# normal imports
import random, math
import animationSets
import keyMap
import messages
import particleEffects
#import cutScenes
import config
import copy
import os
import levelData
import poem
import tutorial
import webbrowser

    
def openWebPage(address):                        
    webbrowser.open_new(address)

class pallet:
    def __init__(self,colour1,colour2,colour3,colour4,colour5):
        self.colour1 = colour1
        self.colour2 = colour2
        self.colour3 = colour3
        self.colour4 = colour4
        self.colour5 = colour5
        
        self.colourArray = [self.colour1,self.colour2,self.colour3,self.colour4,self.colour5]
        self.colourArray.sort(self.sortcolour)
        self.colour1 = self.colourArray[0]
        self.colour2 = self.colourArray[1]
        self.colour3 = self.colourArray[2]
        self.colour4 = self.colourArray[3]
        self.colour5 = self.colourArray[4]
        
    def setColourByIndex(self,index,alpha):
        colour = self.colourArray[index]
        PC.setColour(colour[0],colour[1],colour[2],alpha)
        
    def returnColourByIndex(self,index,alpha):   
        colour = self.colourArray[index]
        return[colour[0],colour[1],colour[2],alpha]
        
    def sortcolour(self,a,b):
        aTotal = a[0] + a[1] + a[2]
        bTotal = b[0] + b[1] + b[2]
        return int(bTotal - aTotal)
    
#    def setColour(colour,alpha):
#        PC.setColour(colour[0],colour[1],colour[2],alpha)

pallet1 = pallet([32,102,63],[37,153,89],[171,212,6],[255,212,18],[255,130,28]) #marmalade

pallet3 = pallet([101,250,75],[204,203,81],[220,155,87],[235,108,92],[250,60,98]) #Tropical
    
pallet2 = pallet([255,136,97],[147,179,100],[182,209,142],[255,182,158],[129,163,78])

pallet4 = pallet([255,238,87],[171,162,85],[89,125,117],[125,71,71],[99,65,76])
    
pallet5 = pallet([204,243,255],[143,229,255],[87,216,255],[41,205,255],[35,176,219])
    
pallet6 = pallet([122,179,23],[11,46,89],[13,103,89],[42,4,74],[160,197,95])
    
pallet7 = pallet([136,22,64],[66,23,51],[123,19,40],[199,18,75],[247,37,69])        
    
pallet8 = pallet([105,210,231],[167,219,216],[224,228,204],[243,134,48],[250,105,0]) 

pallet9 = pallet([247,226,171],[219,189,164],[193,188,162],[125,106,98],[163,179,148]) #nearnesss of you



pallet10 = pallet([157,237,224],[104,212,176],[27,179,103],[41,140,74],[74,140,74]) #listen.to.the.forest

pallet11 = pallet([182,66,69],[217,137,98],[246,203,107],[249,240,199],[111,128,105]) #hidden secret

pallet12 = pallet([255,160,143],[255,202,149],[241,233,214],[205,207,160],[122,134,158]) #loving you is easy

palletList = [pallet1,pallet2,pallet3,pallet4,pallet5,pallet6,pallet7,pallet8,pallet9,pallet10,pallet11,pallet12]


    
    
def setPalletColour(colour,alpha):
    PC.setColour(colour[0],colour[1],colour[2],alpha)
    
copywrite1 = "all game code is copywrite Charlie Dog Games August 2008"        

###########################################
# Application initialization data 
###########################################
appIni = {	"mCompanyName"		: "CDG",
		"mFullCompanyName"	: "Charlie Dog Games",
		"mProdName"		: "AtomicWorm",
		"mProductVersion"	: "0.19",
		"mTitle"			: "Atomic Worm",
		"mRegKey"			: "AtomicWorm",
		"mWidth"			: 800,
		"mHeight"			: 600,
		"mAutoEnable3D"	: 1,
		"mVSyncUpdates"	: 1,
		"mWaitForVSync" : 1, 
                "mWindowIconBMP": "extraResources/Logos/icon.bmp"}

class LevelMetaDataClass:
    title = "temp"
    RandomTiles = 0
    DayTime = 0
    RandomSpawns = 0
    currentSection = None
    currentSectionNumber = 0
    currentLevelFile = None
    platformSet = None
    jewelSet = None
    BackDrop = None
    introMusic = None
    sequence = 0
    instructions = None
    midInstructions = None
    winMusic = None
    loseMusic = None
    scrollSpeed = 0
    randomSpawnEnemy = 0
    nextEnemySpawn = 0
    levelNumber = 0
    
    UpperScenery = []         #This is a sequential list of all the scenery on the bottom - stored as a structure with a name and an X
    LowerScenery = []         #This is a sequential list of all the scenery on the bottom 
    LastX = 10000                    #mock up of the last X coordinate
    title = ""

class MouseOver:
    function = None
    parameter = None
    
lettersGot = 0    
whereIsSnakyJake = -1   
charlieBark = -1
tutorialsOn = 1
thisLevelTutioral = 0
editorScrollBar = 0
maxEditorScrollBar = 60
editorScrolled = 0
double1DownCount = 0
double1Down = 0
double2DownCount = 0
double2Down = 0
pointerSizeX = 8
mouseOverMessage =MouseOver()
globalPlayer = None #dirty trick so we can find the player
globalFairy = None
doExit = 0 # flag specifying whether or not the game should continue to run (not a hook)
allGraphicFiles=[]
allGraphicFilesNames=[]
allSoundFiles=[]
allSoundFilesNames=[]
allLevelFiles=[]
allLevelFilesNames=[]
font8 = None
font20 = None
font22 = None
font22Plain = None
font16 = None
font23 = None
font24 = None
font26 = None
font30 = None
font36 = None
font38 = None
font44 = None
font45 = None
font50 = None

PC = None
time = 0
rotation = 0
oldCameraX = 0
cameraX=0
cameraY = 0
#gameSpeed = 0
x_max = 800
x_min = 0
y_max = 600
y_min = 0
gravity = 0
lives = 0
score = 0
displayScore = 0
collected = 0
collectedTarget = 0
collectedTargetRender = 0
GameOverDelay = 0
startGame = 1  #Game sits in the start up screen until this is cleared
canStart = 0 #hack to allows to check that the enter key is raised between end and start games

nextID = 0
#All the objects in the world
objects = []
solidObjects = [] #list of solid objects which is populated at the beginning of the update loop
unusedObjects = [] # list of all objects which have been created but are not now used

levelMetaData = LevelMetaDataClass()
Enabled = 0

#JPG_resources is populated with all the JPG in the res directory
JPG_Resources = {}
WAV_Resources = {}
map_Resources = {}
MIDI_Resources = {}
map_Section = {}
map_Jewels = {}
buttonExtents = {}
inEditor = 0
InEditorKeyUP = 0
CursorY = 0
nextObjectIndex = 0
ObjectStarts = []

PCR = None
levelNumber = startingLevel
FinishFlag = 0
ExitFlag = 0
FinishTimer = 0

ScreenMessages = None
keyArray = range(512)
keyRepeatArray = range(512)
downKey= 0
metaGame= 0
gamePaused = 0

oldMetaGame =99999
scorePos = -1
newGame = 0
fullRotation = 44.0/7.0
tempDelta = 0
totalTimePlayed = 0
gameLife = 0

mdx = 0
mdy = 0
mdn = 0
mousex = 0
mousey = 0
mouseWheelPos = 0
mouseDelta = 0
inGUI = 0

dataIsLoaded=0
loadingScreen = None
loadingBar = None
fileIndex = 0
gameOver = 1
scoreX = 5 # postion of score on the screen for printing and moving the coins
scoreY = 45
startLevelTimer = 0 
fullScreenMode = 0
delayRefill = 0
currentProfile = 0      #this needs saving and loading in the registry

StagingFlag = 0
forcePause =0

levelTime = 0
levelTimeDelta = 0

button1Down = 0

startLives = 3
levelQueued = 0
continousTime = 0       #incremented each frame
nextLifeScoreTarget = 0
cursorEnabled = 1

instructionWait = 0
finishOn = 0
thisHighScoreIDX=100
quietMusic = 0.25
gGameOver = 0
addStrobe = 0
subtractStrobe = 10
multiplyStrobe = 20
divideStrobe = 30
arcadeMode = 0
speedMode = 0
puzzleMode = 1
globalSoundCount = 0
currentPoem = poem.poem1

# Initialises all global variables in here.  Called at the start of every new game
###########################################
def initialiseGame():
    global mouseEnabled
    global gamePaused
    global metaGame
    global lives
    global score
    global displayScore
    global levelNumber  
    global time 
    global ScreenMessages  
    global objects
    global keyArray
    global keyRepeatArray
    global oldMetaGame
    global scorePos
    global newGame
    global gameOver
    global startGame
    global arcadeMode 
    global thisHighScoreIDX
    metaGame= menuItems.mainScreenCanvas
    thisHighScoreIDX = 100

    for key in xrange(512):
        keyArray[key] = 0
        keyRepeatArray[key] = 0 

    gameOver = 1
    mouseEnabled= 1
    oldMetaGame=0
    scorePos=-1
    time = 0
    objects = []  #Clear all the existing objects in the world
    random.seed(1)
    ScreenMessages = ScreenMessagesClass()
    fadeManager.fadeDown(menuItems.nameCanvas)
    game.setUpGameClass()
  
    
###########################################
# mouseEnter
#
# Notifier called whenever the mouse enters
# the app window
#
###########################################
def mouseEnter():
	global gamePaused
        if(gamePaused==1):
            gamePaused = 0
        forceSoundUpdate()
        #if(escapeMenu.active):
        #    escapeMenu.active = 0

###########################################
# mouseLeave
#
# Notifier called whenever the mouse leaves
# the app window
#
###########################################
def mouseLeave():
	global gamePaused
	gamePaused = 1
        #if escapeMenu.active == 0:
         #   escapeMenu.toggle()

###########################################
# mouseMove
#
# Notifier called whenever the mouse moves
# inside the app window
#
###########################################
def mouseMove( x, y ):
	# store for render
	global mousex, mousey
        if game:
            game.inputMode = 0
	mousex = x
	mousey = y
        if(inEditor):
            moveSelected(x,y)
#        if(inGUI):
        if ScreenMessages != None:
            ScreenMessages.mouseInput(x,y,-1)

def makeSparkleParticle(x,y,deltaX,deltaY,maxSize=1):
    deltaX += 0.5-(random.randint(0,10)/10.0)
    deltaY -= (random.randint(0,10)/20.0)
    size = .5 + (random.randint(0,10)/100.0)
    size *= maxSize
    particleChosenIndex = random.randint(1,2)
    if particleChosenIndex==1:
        particleChosen = fairySparleParticle1()
    else:
        particleChosen = fairySparleParticle2()
    particleController.addItem(particleChosen,x,y,size,deltaX,deltaY)
 
def makeGhostParticle(x,y,deltaX,deltaY,maxSize,diameter):
    deltaX += 0.5-(random.randint(0,10)/10.0)
    deltaY -= (random.randint(0,10)/20.0)
    angle = random.randint(0,100) * 44/700.00
    x += diameter/2*math.sin(angle)
    y += diameter/2* math.cos(angle)
    size = 1.0
    particleChosen = ghostParticle()
    particleController.addItem(particleChosen,x,y,size,deltaX,deltaY)

def makeAttackParticle(x,y,deltaX,deltaY,maxSize,h_bias,v_bias):
    deltaX += -1.5 + (random.randint(0,30)/10.0)
    deltaY -= (random.randint(0,30)/10.0)
    size = .5 + (random.randint(0,10)/20.0)
    x += (h_bias * -0.5) + random.randint(0,int(h_bias))
    y += (v_bias * -0.5) + random.randint(0,int(v_bias))
    size *= maxSize
    particleChosenIndex = random.randint(1,2)
    if particleChosenIndex==1:
        particleChosen = fairyAttackParticle1()
    else:
        particleChosen = fairyAttackParticle2()
    particleController.addItem(particleChosen,x,y,size,deltaX,deltaY)
    
def makeFireWorkParticle(x,y,deltaX,deltaY,maxSize,h_bias,v_bias): 
    deltaX += -1.5 + (random.randint(0,30)/10.0)
    deltaY -= (random.randint(0,30)/10.0)
    size = .5 + (random.randint(0,10)/20.0)
    x += (h_bias * -0.5) + random.randint(0,int(h_bias))
    y += (v_bias * -0.5) + random.randint(0,int(v_bias))
    size *= maxSize
    particleChosenIndex = random.randint(1,100)
    if particleChosenIndex<70:
        particleChosen = fireWorkParticle1()
    elif particleChosenIndex<92:
        particleChosen = fireWorkParticle2()
    else:
        particleChosen = fireWorkParticle3()
    particleController.addItem(particleChosen,x,y,size,deltaX,deltaY)
    
class pointer:
    image1 = None
    image2 = None
    xSize = 60
    ySize = 60
    xOffset = -18
    yOffset = -30
    enabled = 1
    targetAlpha = 255
    currentAlpha = 0
    oldX = 0
    oldY = 0
    deltaX = 0
    deltaY = 0
    clicked = 0
    nextSparkle = 10
    oldCameraX = 0
    
    def tick(self,delta):
        size = 0.25
        scrollDelta = (cameraX - self.oldCameraX)/delta
        self.oldCameraX = cameraX
        if self.clicked>0:
            size *= 4.0
            particle = fairyTrailParticle()
            self.clicked -= delta
        else:
            particle = fairyRedTrailParticle()
            if self.clicked <0:
                self.clicked = 0
        #distance = math.sqrt((self.deltaX * self.deltaX) + (self.deltaY * self.deltaY))
        deltaX = (mousex - self.oldX)/8.0
        deltaY = (mousey - self.oldY)/8.0
        if dataIsLoaded and gamePaused ==0 and self.enabled and renderDetailLevel>0:
            particleController.addItem(particle,cameraX+self.oldX,self.oldY,size,deltaX+ scrollDelta,deltaY)
            self.nextSparkle -= delta
            if self.nextSparkle<0:
                self.nextSparkle = 5
#                makeSparkleParticle(cameraX+self.oldX,self.oldY,deltaX+scrollDelta,deltaY)

        if self.enabled == 0:
            self.targetAlpha = 0
        else:
            self.targetAlpha = 255
        if self.currentAlpha > self.targetAlpha:
            self.currentAlpha -= delta*10
        if self.currentAlpha < 0:
            self.currentAlpha = 0
        if self.currentAlpha < self.targetAlpha :
            self.currentAlpha += delta*10
        if self.currentAlpha > 255:
            self.currentAlpha = self.targetAlpha     

    def stop(self):
        self.targetAlpha = 0
        self.currentAlpha = 0
        self.enabled = 0

    def render(self):
        x = mousex
        y = mousey
        self.deltaX = self.oldX-x
        self.deltaY = self.oldY-y
        self.oldX = x
        self.oldY = y
        direction = 1
        xOffset = self.xOffset
        if gamePaused ==0:  #mouse has left the game
            PC.setColourize(0)
            pointerName = self.image1
            if continousTime%10>5:
                pointerName = self.image2
            frame = JPG_Resources[pointerName]
            PC.setColourize(1)
            PC.setColour(255,255,255,self.currentAlpha) 
            if globalPlayer != None and metaGame == menuItems.game: 
                if x+cameraX < globalPlayer.x+(self.xSize+globalPlayer.width)/2:
                    direction = -1
                    xOffset = -2*self.xOffset
            PC.drawImageScaled(frame, x+xOffset, y+self.yOffset,direction*self.xSize,self.ySize )  
            PC.setColourize(0)
            
class fairyPointerClass(pointer):
    image1 = "Mouse01"
    image2 = "Mouse02"
    xSize = 32
    ySize = 40
    xOffset = -2
    yOffset = -9
    
class arrowPointerClass(pointer):
    image1 = "Mouse02"
    image2 = "Mouse02"
    xSize = 30
    ySize = 30
    xOffset = 0
    yOffset = 0    
    enabled = 0

fairyPointer = fairyPointerClass()
arrowPointer = arrowPointerClass()

def tickCursors(delta):
    return
    fairyPointer.tick(delta)
    arrowPointer.tick(delta)

def renderCursors():
    return
    fairyPointer.render()
    arrowPointer.render()
    
mouseToggle = 0

###########################################def mouseDown( x, y, i ):
	# store for render
def mouseDown( x, y, i ):
        global mdx, mdy, mdn,mouseToggle
        global editorAddObject
        global button1Down
        global double1DownCount
        global double1Down
        global double2DownCount
        global double2Down
        global smartBombCount
        global instructionWait

        if instructionWait==1:
            instructionWait = 0
        doubleClickDelay = 30
	mdx = x
	mdy = y
	mdn = i
        button1Down = 0
        button2Down = 0
        if metaGame:
            menuClasses[metaGame].mouseClick(i)
        elif game:
            game.mouseDown(mdn)
        if(mdn ==0):    #check to see if player is clicking on a message
            if ScreenMessages:
                ScreenMessages.mouseInput(x,y,1)

###########################################
# mouseUp
#
# Notifier called whenever a mouse button
# is released
#
###########################################
def mouseUp( x, y, i ):
	# store for render
	global mux, muy, mun,mouseToggle
        global inGui
        global button1Down
        global instructionWait
	mux = x
	muy = y
	mun = i
        button1Down = 0
        mouseToggle = 0
        if(inEditor and mdn == 0): #left button
                updateSelection(x,y,0)

class StringInput:
    thisString = ''
    length = 128
    def addChar(self,char):
        if(char == keyMap.backSpace.keyValue):
            self.thisString = self.thisString[:-1]
        elif(char == keyMap.spaceKey.keyValue): #space pressed
            self.thisString = self.thisString+chr(32)
        else:
            if ( (len(self.thisString)<self.length-1) and (char >= ord("a") and char <= ord("z") ) or ( char >= ord("A") and char <= ord("Z") ) or ( char >= ord("0") and char <= ord("9") ) ):
                if(char>=ord('a') and char <=ord('z')):
                    if((checkKey(keyMap.leftShiftKey.keyValue)==0) and (checkKey(keyMap.rightShiftKey.keyValue)==0) ):
                        self.thisString = self.thisString+chr(char).lower()
                    else:
                        self.thisString = self.thisString+chr(char).upper()
                else:
                    self.thisString = self.thisString+chr(char)
    def clearString(self):
        self.thisString=''
        
    def getDisplayString(self):
        string = self.thisString
        if continousTime%100<50:
            string += "___________________"
        return string[:self.length-1]
  
workingString = StringInput()

def scoreWithIcon(x,y,worth):
    incScore(worth)


def clamp255(byte):
    if byte>255:
        return 255
    elif byte < 0:
        return 0
    return byte
    
def clamp0(value,check):
    if value>check:
        return check
    elif value < 0:
        return 0
    return value
    
class ScreenMessage:
    string = None
    tabX = 500
    tabY = 100
    R =  0
    G =  0
    B =  0
    A =  255   
    width = 0
    height = 0
    stringTime = 500
    scroll = 0
    font = None
    mouseDown = 0
    mouseOver = 0
    function = None
    graphic = None
    parameter = None
    forceFade = 0
    fadeUpTime = 0
    mouseOverfunction = None
    collisionX = 0
    collisionWidth = 0
    particleOnStrobe = 0
    scale = 1.0
    life = 0
    flashEnabled = 1
    graphicRes = -1
    enabled = 1
    hideIcon = 0
    
    def RenderMessage(self):
        a = 255
        if self.enabled ==0:
            return
        if PCR == None or PC == None:
            return
        self.collisionX = self.tabX
        self.collisionWidth = self.width
        PC.setColourize(0)
        if self.function and inEditor==0: 
            flash = 18 + math.sin((self.tabY/10+continousTime)/9)*20
        else:
            flash = 0

        
        if(self.string != None and self.string != ""):
            highLightString = None
            right = 0
            workingString = self.string
            HighLight = workingString.find('__H')
            if HighLight != -1:
                HighLightDown = workingString.find('__N')
                right = workingString[:HighLight]
                left = workingString[HighLightDown+3:]
                highLightString = workingString[HighLight+3:HighLightDown]
                workingString = "%s%s%s" % (right,highLightString,left)
            widthDelta = 0
            font = self.font
            hint = flash
            if (self.mouseOver and inEditor==0):
                hint  = 60
                if font == font16:
                    font = font16
                elif font == font26:
                    font = font30
                else:
                    font = font44
            if font == None:
                return
            if self.string == None:
                return
            if self.graphicRes == -1:
                print "font index", font
                self.width = PCR.stringWidth(workingString,font)
                self.height = PCR.fontAscent(font)
            if(self.tabX == -1):
                self.tabX = ((800-self.width)/2)
                
            unselectedwidth = PCR.stringWidth(workingString,self.font)

            a = int(self.A-32)
            alpha = self.A
            if self.fadeUpTime:
                alpha = self.A * (self.fadeTimer/self.fadeUpTime)
                a = int(alpha-32)
            
            PC.setFont(font)
            if(inEditor==0):
                y = self.tabY
            else:
                y = self.tabY+ 20
            if a>=0:
                PC.setColour( 0,0,0,a )
                PC.drawString( workingString,self.tabX+2-widthDelta, y+2 )    
            if(self.mouseDown):
                 PC.setColour( 255, 0, 0, alpha )              
            else:        
                PC.setColour( clamp255(self.R+hint), clamp255(self.G+hint), clamp255(self.B+hint),clamp255(alpha+hint) )
            PC.drawString( workingString, self.tabX-widthDelta, y )
            if highLightString:
               # alpha = clamp255(200 + math.sin(self.life/5.0)*50)
                PC.setColour( 255,0,0,alpha)
                highLightOffset = PCR.stringWidth(right,font)
                PC.drawString( highLightString, self.tabX-widthDelta+ highLightOffset, y )            
        if(self.graphicRes == -1):
            if self.function and a>0:
                PC.setColourize(1)
                PC.setColour( 255,255,255,a )
                PC.drawmodeNormal()
                graphicName = JPG_Resources["button"]
                y = self.tabY - PCR.imageHeight( graphicName )
                x = self.tabX - PCR.imageWidth( graphicName )-5
                width = PCR.imageWidth( graphicName )
                height = PCR.imageHeight( graphicName )
                if self.mouseOver:
                    y += height
                    graphicName = JPG_Resources["buttonBig"]
                    width = PCR.imageWidth( graphicName )
                    height = PCR.imageHeight( graphicName )
                    y -= height
                if self.hideIcon == 0:
                    PC.drawImageScaled( graphicName, x, y,width,height)
                self.collisionX -= 40
                self.collisionWidth += 40
        else:
            graphicName = self.graphicRes  
            renderWidth = self.width * self.scale
            renderXOffset = 0
            renderHeight = self.height * self.scale
            renderYOffset = 0
            if inEditor ==0  and self.mouseOver:
                renderWidth *= 1.2
                renderHeight *= 1.2
                renderXOffset = (renderWidth-(self.width*self.scale))/2.0
                renderYOffset = (renderHeight-(self.height*self.scale))/2.0 
            PC.setColourize(1)
            PC.drawmodeNormal()
            if self.mouseOver or self.flashEnabled==0:
                colour = 255
            else:
                colour = clamp255(160+(flash*3))
            PC.setColour( colour, colour,colour, 255)
            PC.drawImageScaled( graphicName, self.tabX-renderXOffset, self.tabY-renderYOffset,renderWidth,renderHeight)
            if self.mouseOver:
                PC.drawmodeAdd() 
                if inEditor:
                    PC.setColour( 255, 255,255, 180)
                    PC.drawImage( graphicName, self.tabX, self.tabY)
                else:
                    PC.setColour( 255, 255,255, 55)
                    PC.drawImageScaled( graphicName, self.tabX-renderXOffset, self.tabY-renderYOffset,renderWidth,renderHeight)
                if self.mouseOverFunction:
                    mouseOverMessage.function = self.mouseOverFunction
                    mouseOverMessage.parameter = self.parameter
                else:
                    self.mouseOverMessage = None
                
                x1 = random.randint(0,int(renderWidth)) 
                x1 += self.tabX-renderXOffset
                y1 = random.randint(0,int(renderHeight)) 
                y1 += self.tabY-renderYOffset
                bias = (renderWidth/2.0 - x1)/-300.0
                makeSparkleParticle(x1,y1,bias,0,renderWidth/90.0) 

            if (inEditor and self.string != None and self.string != ""):
                PC.setColour( 255, 0, 0, alpha ) 
                PC.drawString( self.string, self.tabX, y )  
    
    def setMessage(self,message,R,G,B,A,font,tabY,scroll,tabX,function,graphic,parameter,fadeUpTime,mouseOverFunction=None,scale = 1.0,flashEnabled=1):
        self.mouseOverFunction = mouseOverFunction
        self.string = message
        self.tabY = tabY
        self.R = R
        self.G = G
        self.B = B
        self.A = A
        self.tabX = tabX
        if graphic == -2: 
            graphic = None
            self.hideIcon = 1
        self.graphic = graphic
        if graphic:            
            if(inEditor and (self.width>38 or self.height>38)): 
                if(self.width>self.height):
                    self.height *= 38.0/self.width
                    self.width = 38
                else:
                    self.width *= 38.0/self.height
                    self.height = 38  
                    
        self.function = function
        self.parameter = parameter
        self.scale = scale
        self.flashEnabled = flashEnabled
        if graphic == -2:
            self.graphicRes = -2
        if font == 8:
            self.font = font8  
        elif font == 16:
            self.font = font16
        elif font == 36:
            self.font = font44
        elif font == 22:
            self.font = font26
        elif font == 48:
            self.font = font44
        else: 
            font = font22
        #    print "error font not know in set message!"
          
        self.scroll = scroll
        self.fadeUpTime = fadeUpTime
        self.fadeTimer = 0

    def tickMessage(self,delta):
        self.life += 1

        if self.fadeUpTime:
            self.fadeTimer += delta
            if self.fadeTimer > self.fadeUpTime:
                self.fadeTimer  = self.fadeUpTime
        if(self.scroll):
            self.tabY -= delta/2.0
            if(self.tabY<70):
                self.A-= delta*3
            if(self.A <=0):
                self.string = None

                
    def setFade(self):
        self.forceFade = 1
        TEMP = 1
            
class ScreenMessagesClass:    
    message = ScreenMessage()
    messages = []
    lastMessageTabY = 0

    def RenderMessages(self):
        for message in self.messages:
            message.RenderMessage()
        PC.drawmodeNormal()
        PC.setColourize(0)
            
    def clearMessages(self):
        self.messages = []
        self.lastMessageTabY = 0 #tony - experiment

    def setMessageScroll(self,message,graphic,string=None,parameter=None,function = None,fadeIn=0,mouseOverFunction = None):
        newMessage = ScreenMessage()
        thisString = message[0]
        tabY = 120
        if(tabY-self.lastMessageTabY<40):
            tabY = self.lastMessageTabY+40
        self.lastMessageTabY = tabY
        if(string != None):
            thisString = thisString+string
        sound = message[1]
        if sound != None:
            playSimpleSound(sound)
        tabX = -1       #we may want to be able to fix this
        scroll = 1
        newMessage.setMessage(thisString,message[2],message[3],message[4],message[5],message[6],tabY,scroll,tabX,function,graphic,parameter,fadeIn,mouseOverFunction)
        self.messages.append(newMessage)

    def setMessageStatic(self,message,graphic,x,y,function,string=None,parameter=None,fadeUp=0,mouseOverFunction = None,scale = 1.0,flashEnabled = 1):
        scroll = 0
        newMessage = ScreenMessage()
        thisString = message[0]
        if(string != None):
            thisString = thisString+string
        playSimpleSound(message[1])
        newMessage.setMessage(thisString,message[2],message[3],message[4],message[5],message[6],y,scroll,x,function,graphic,parameter,fadeUp,mouseOverFunction,scale,flashEnabled)
        self.messages.append(newMessage)
        return newMessage

    def tickMessages(self,delta):
        self.lastMessageTabY -= delta/2.0
        for message in self.messages[:]:
            message.tickMessage(delta)
            if message.string == None:
                self.messages.remove(message)
            if message.forceFade:
                message.A -= delta*2
                if message.A <0:
                    message.A = 0
                
    def mouseInput(self,mouseX,mouseY,button):
        for message in self.messages:
#            if message.scroll == 0:
                message.mouseOver = 0
                message.mouseDown= 0
                if(message.graphic != None):
                    localY= message.tabY+message.height
                else:
                    localY= message.tabY
                if(message.function != None and mouseX> message.collisionX and mouseX < message.collisionX+message.collisionWidth):                
                    if(mouseY< localY and mouseY > localY-message.height): 
                        if(button == -1): #mouse has moved
                            message.mouseOver = 1
                        if(button == 1):
                            message.mouseDown = 1
                            if(message.function!= None):
                                playSimpleSound("mouseClick")
                                if(message.parameter != None):
                                    message.function(message.parameter)
                                else:
                                    message.function()
                                    
    def RenderMessageDirect(self,X,Y,string,alpha,extra_string=None):
        thisString = string[0]
        if(extra_string != None):
            thisString = thisString+extra_string
        playSimpleSound(string[1])
        R=string[2]
        G=string[3]
        B=string[4]
        A=string[5]* alpha/255.0
        fontID = string[6]
        if fontID == 8:
            font = font8           
        elif fontID == 36:
            font = font36
        elif fontID == 22:
            font = font22
        else: 
            font = font22
        if(X==-1):
            X = ((800-PCR.stringWidth(thisString,font))/2)
        PC.setColour( 0,0,0,128 * alpha/255.0 )
        PC.setFont(font)
        PC.drawString( thisString, X+3, Y+3 )
        PC.setColour( R, G, B, A )
        PC.drawString( thisString, X, Y )
        
    def fadeAndClear(self):
        for message in self.messages:
            message.setFade()
        self.lastMessageTabY = 0 #tony - experiment
        
 
def loadResources(delta):
    global dataIsLoaded
    global whereIsSnakyJake
    global charlieBark
    
    if charlieBark>=0 and logoCount< 300:
            PC.playSound( charlieBark,0.5,0,0)  
            charlieBark = -1
#    if whereIsSnakyJake>=0 and fileIndex>100:
#            PC.playSound( whereIsSnakyJake,0.5,0,0)  
#            whereIsSnakyJake = -1
    if pubLogoCount > 0:
        tickpubLogo(delta)
        return
    if logoCount >0:
        tickLogo(delta)
        return
    unloadLogoGFX()
    tickLoading(delta)
    if(len(allGraphicFiles)==0):
        getFileNames('res/')
    else:
        loadGraphicsFromList()
        uncrunchMusic()        
        PC.markDirty()
    if(dataIsLoaded):
        loadSounds('res/')
        initialiseGame() 
        unloadLoadingScreen()
        uncrunchMusic()
#        game.loadAllLevels()
        

def getFileNames(root):
    import os
    global allGraphicFiles
    global allGraphicFilesNames
    files = [] 
    files = os.listdir(PC.getAppResourceFolder() + root)
    for file in files:
        dot = None
        extension = file[-3:]
        name = file[:-4]
        if extension == "JPG" or extension == "jpg" or extension == "PNG" or extension == "png":
            if name[-1] != "_":  #don't load include the masks in the list...
                allGraphicFiles.append(root+file)
                allGraphicFilesNames.append(file)
        if extension == "jld":
            allGraphicFiles.append(root+file)
            allGraphicFilesNames.append(file)
        if extension == "mid" or extension == "MID":
            allGraphicFiles.append(root+file)
            allGraphicFilesNames.append(file)
        found= file.find(".")
        if(found == -1):
            getFileNames(root+file+"/")

 ###########################################
# loadMap
###########################################
GSection = 0
GJewels = 0

def loadMap(file):
    #print ("level file",file)
    global GSection 
    global GJewels
    newMapLevel = []
    openFile = open(PC.getAppResourceFolder() + file, "r" )
    newRecord = []
    count = 0
    for line in openFile:
      if(count==0):
          GSection = int(line)
      elif(count==1):
          GJewels = int(line)
      elif(line=="RecordEnd\n"):
          newMapLevel.append(newRecord)            
          newRecord = []
      else:
          newRecord.append(float(line))
      count += 1
    return newMapLevel
    
 ###########################################
# loadGraphics
###########################################
def loadGraphicsFromList():
    import os
    import PycapRes
    global PCR
    global fileIndex
    global dataIsLoaded 
    PCR = PycapRes
    toLoad = len(allGraphicFilesNames)-fileIndex-1
    if(toLoad>5):
        toLoad = 5 #load data 5 files at a time.
    while toLoad>=0:
        dot = None
        file = allGraphicFiles[fileIndex]
        fileName = allGraphicFilesNames[fileIndex]
        fileIndex+=1
        extension = fileName[-3:]
        name = fileName[:-4]
        fileNoExtension = file[:-4]
        if extension == "JPG" or extension == "jpg" or extension == "PNG" or extension == "png" :
            JPG_Resources[name] = PCR.loadImage( fileNoExtension)
            #print "loading image",name,JPG_Resources[name]
        if extension == "jld":
            map_Resources[name] = loadMap(file)
            map_Section[name] = GSection        #horrid hack
            map_Jewels[name] = GJewels
        if extension == "mid" or extension == "MID":
            MIDI_Resources[name] = PCR.loadTune(file)
         #   print"loading midi",file
        toLoad -= 1
    if fileIndex >= len(allGraphicFilesNames)-1:
        dataIsLoaded = 1

###########################################
# loadSounds
###########################################
def loadSounds(root):
    import os
    import PycapRes
    global PCR
    PCR = PycapRes
    files = [] 
    files = os.listdir(PC.getAppResourceFolder() + root)
    #print("checking path ",root)
    for file in files:
        dot = None
        #print "found ",file
        extension = file[-3:]
        name = file[:-4]
        if extension == "WAV" or extension == "wav" or extension == "ogg" or extension == "OGG":
        #    print "loading resource ",file
            WAV_Resources[name] = PCR.loadSound( root+name )
        found= file.find(".")
        if(found == -1):
            loadSounds(root+file+"/")
    
###########################################
# loadBase
# Called when resource handler is created.
# Should be used to populate it with basic
# resources required by the game.
#
# Simple games can do all their loading
# here.
###########################################
logoScreen = None
logoText1 = None
logoText2 = None
logoBack = None
pubLogo = None
logoLoaded = 0
loadingScreenLoaded = 0
uncrunchIndex=-30

levelMusic = ['Level3',"level2","level4"]

def uncrunchMusic():
    global fileIndex
    global uncrunchIndex
    step = 15  #tony - this is set up so that it will uncrunch all the music when all files are loaded
    index = uncrunchIndex/step
    if index >=0 and index < len(levelMusic) and uncrunchIndex%step==0:
        song = levelMusic[index]
        file= 'extraResources/Music/'+song
        print "loading music ",file
      	tempMusic =  PCR.loadSound( file )
        PCR.unloadSound(tempMusic) 
    uncrunchIndex += 1


def unloadLogoGFX():
    import PycapRes
    global logoLoaded 
    if logoLoaded:
        PycapRes.unloadImage(logoScreen)
        PycapRes.unloadImage(logoText1)
        PycapRes.unloadImage(logoText2)
        PycapRes.unloadImage(logoBack)
#        PycapRes.unloadImage(pubLogo)
        logoLoaded = 0

def unloadLoadingScreen():
    global loadingScreenLoaded
    if loadingScreenLoaded:
        PCR.unloadImage(loadingScreen)
        PCR.unloadImage(loadingBar)
        loadingScreenLoaded = 0
         
def loadBase():
	#print "loadBase called"
        import Pycap
	global PC
        global loadingScreen
        global loadingBar
        global logoScreen
        global logoText1
        global logoText2
        global logoBack
	PC = Pycap
	import PycapRes
	global res
        global pubLogo
        global whereIsSnakyJake
        global charlieBark
        global PCR
        PCR = PycapRes
        setLocalAppData()             
        if showAllLogo:
            charlieBark = PycapRes.loadSound( 'res\sounds\charlieBark.ogg')
#            whereIsSnakyJake = PycapRes.loadSound( 'res\sounds\whereIsSnakyJake')
        if showNonFreeLogos:
            logoScreen = PycapRes.loadImage('extraResources/Logos/Logo.jpg')
            logoText1 = PycapRes.loadImage('extraResources/Logos/LogoText1.jpg') 
            logoText2 = PycapRes.loadImage('extraResources/Logos/LogoText2.jpg') 
            logoBack = PycapRes.loadImage('extraResources/Logos/Bgrnd.jpg') 
            global logoLoaded 
            logoLoaded = 1
        if showNonFreeLogos:
            pubLogo= PycapRes.loadImage('extraResources/Logos/tweeler.png') 

        global loadingScreenLoaded
        loadingScreenLoaded = 1
        loadingScreen = PycapRes.loadImage('extraResources/loading/loading.jpg')
        loadingBar = PycapRes.loadImage('extraResources/loading/JakeLoading.jpg')
        #print"loadingScreen"
	global font22
        global font22Plain
        global font23
        global font24
        global font26
        global font36
        global font30
        global font38
        global font45
        global font50
        global font8
        global font20
        global font44
        global font16
        font44 = PycapRes.loadFont( "res/font/Impact44.txt" )       
        font8= PycapRes.loadFont( "res/font/Arial8.txt" )
        font26 = PycapRes.loadFont( "res/font/Impact26.txt" )
        font30 = PycapRes.loadFont( "res/font/Impact30.txt" )
        font36 = PycapRes.loadFont( "res/font/Impact36.txt" )
        font16 = PycapRes.loadFont( "res/font/Impact16.txt" )
        print "font16",font16
        highScoreCanvas.initialiseScores()
 
###########################################
# init
#
# Called when the game board is created,
# after resources have loaded. Set the 
# initial game state here.
#
###########################################
def init():
	#print "init called"
        global totalTimePlayed
        global currentProfile

	# load the pycap module
        #openUrl('http://tycho.usno.navy.mil/cgi-bin/timer.pl')          
        #All the game initialisation is done in here so that it can be redone when the game restarts after a game over
        #initialiseGame()
        regEntry = PC.readReg( "cheats" ) 
        if regEntry:
            cheatCanvas.active = int(regEntry)
        regEntry = PC.readReg( "totalTimePlayed" ) 
	if regEntry:
            totalTimePlayed = int(regEntry)
            totalTimePlayed *= 100
        else:
            #this will happen if the game has never been run before
            PC.setFullscreen(0)
            
        readProfiles()

        savedProfile = PC.readReg("CurrentProfile")
        savedVersion = PC.readReg("Version")
        if savedVersion:
           savedVersion = int(savedVersion)
        else:
            savedVersion = -1
        if savedProfile:
            currentProfile = int(savedProfile)
        if savedVersion != currentVersion:
            #print "clearing profile",savedVersion, currentVersion
            currentProfile = 0
            for profile in profiles:
                profile.ressetProfile()
        PC.showMouse(cursorEnabled)
#        regEntry = PC.readReg( "hardware" ) 
#	if regEntry:
 #           if regEntry == "0":
  #              PC.set3DAccelerated(0)
   #         else:
        #PC.set3DAccelerated(1)
        regEntry = PC.readReg( "renderDetail" ) 
	if regEntry:
            global renderDetailLevel
            renderDetailLevel = int(regEntry)

###########################################
# fini
#
# Called when the game board is destroyed.
# Clean up game state here.
#
###########################################
def fini():
	#print ("fini called")
        #print("Wrote time played",str(int(totalTimePlayed/100)))
        highScoreCanvas.writeScores()
        PC.writeReg( "totalTimePlayed",str(int(totalTimePlayed/100)))
        keyMap.saveKeysRegistry()
        writeProfiles()
        PC.writeReg("CurrentProfile",str(currentProfile))
        PC.writeReg("Version",str(currentVersion))
        PC.writeReg("cheats",str(int(cheatCanvas.active)))
#        hardwareSupport = PC.getIs3DAccelerated()
 #       PC.writeReg("hardware",str(int(hardwareSupport)))
        PC.writeReg("renderDetail",str(int(renderDetailLevel)))
###########################################
# PlayMusic
#Wrapper for PC.PlayMusic
def playTune( tuneName):
    tune = MIDI_Resources[tuneName]
    PC.playTune(tune,2)
    setMusicVolume()

currentTunePlaying = None
nextTuneToPlay = None
tuneVolume = 0
killTune = 0
gLooping = 0
gFadeSpeed = 0.03
gFadeTune = 0
gCurrentPitch = 0
gTargetPitch = 0
targetVolume = 0
instance = 1
oldInstance = 0
oldInstanceVolume = 0

def playTuneOgg( tuneName,looping,fadeSpeed = 0.005):
    global nextTuneToPlay
    global gLooping
    global gFadeSpeed
    global gFadeTune
    global currentTunePlaying
    global oldInstance
    global instance
    global oldInstanceVolume
    
    oldInstance = instance
    oldInstanceVolume = tuneVolume
    instance += 1
    if instance > 1:
        instance = 0
    if gFadeTune:
        gFadeTune = 0

#        PC.playSoundInstance( currentLoadedMusic,0,0, 0,1,instance)
        PC.playTune( currentLoadedMusic, 1)
        
    if tuneName:
        nextTuneToPlay = tuneName
        gLooping = looping
        gFadeSpeed = fadeSpeed
        gFadeTune = 0

    else:
        stopTuneOgg()
    
currentLoadedMusic = -1
currentLoadedName = ""

def checkLoadedMusicOgg(tuneName):
    global currentLoadedMusic
    global currentLoadedName

    if currentLoadedName != tuneName:        
        if currentLoadedMusic != -1:
            PCR.unloadTune(currentLoadedMusic)
        currentLoadedMusic = PCR.loadTune( "extraResources/music/"+tuneName)
        currentLoadedName = tuneName
        
def tuneTick(delta):
    global currentTunePlaying
    global nextTuneToPlay
    global tuneVolume
    global killTune
    global gFadeTune
    global gCurrentPitch
    global gTargetPitch
    global targetVolume
    global oldInstanceVolume
    pitch = 0
    pan = 0
    if nextTuneToPlay:
        panning = 1
        checkLoadedMusicOgg(nextTuneToPlay)
  #PC.playSoundInstance( currentLoadedMusic,0,pan, 0,gLooping,instance) 
        PC.playTune( currentLoadedMusic, gLooping)
 
        tuneVolume = 0        
        currentTunePlaying = nextTuneToPlay
        nextTuneToPlay = None
        gFadeTune = 0
        killTune = 0
        gCurrentPitch = 0
        gTargetPitch = 0
        targetVolume = 1

    if (currentTunePlaying and nextTuneToPlay) or (currentTunePlaying and killTune):   
        tuneVolume -= delta * gFadeSpeed
       # print "fading down",tuneVolume
        if tuneVolume <= 0:
            tuneVolume = 0
            currentTunePlaying = None
        newTuneVolume = profiles[currentProfile].musicVolume*0.25 * tuneVolume
#        PC.setSoundInstance( newTuneVolume,pan, gCurrentPitch,instance) 
        PC.setVolume( newTuneVolume) 
    elif currentTunePlaying:
        if tuneVolume<targetVolume:
            tuneVolume += delta * gFadeSpeed
            if tuneVolume > targetVolume:
                tuneVolume = targetVolume
        if tuneVolume>targetVolume:
            tuneVolume -= delta * gFadeSpeed
            if tuneVolume < targetVolume:
                tuneVolume = targetVolume
        newTuneVolume = profiles[currentProfile].musicVolume*0.25 * tuneVolume
 #       PC.setSoundInstance( newTuneVolume,pan, gCurrentPitch,instance)   
        PC.setVolume( newTuneVolume) 
        if gCurrentPitch<gTargetPitch:
            gCurrentPitch += delta/20.0
            if gCurrentPitch > gTargetPitch:
                gCurrentPitch = gTargetPitch
        if gCurrentPitch>gTargetPitch:
            gCurrentPitch -= delta/20.0
            if gCurrentPitch < gTargetPitch:
                gCurrentPitch = gTargetPitch
                      
        if oldInstanceVolume  > 0: 
            oldInstanceVolume -= delta * gFadeSpeed*2.0
            if oldInstanceVolume < 0:
                oldInstanceVolume = 0  
            newTuneVolume = profiles[currentProfile].musicVolume*0.25 * oldInstanceVolume                
#            PC.setSoundInstance( newTuneVolume,pan, gCurrentPitch,oldInstance)             
            PC.setVolume( newTuneVolume) 


def stopTuneOgg():
    global killTune
    killTune = 1
    
def stopTuneOggComplete():
    global killTune
    global tuneVolume
    killTune = 1
    tuneVolume = 0

        
def setTargetpitch(target):
    global gTargetPitch
    gTargetPitch = target
    
def incTargetpitch(inc):
    global gTargetPitch
    gTargetPitch += inc
    
def setTargetVolume(target):
    global targetVolume
    targetVolume = target
    
def forceSoundUpdate():
    global tuneVolume
    if PC == None:
        return
    pan = 0
    if currentTunePlaying:
        playTuneOgg(currentLoadedMusic, gLooping)
#        PC.playTune( currentLoadedMusic, gLooping)
#        PC.playSoundInstance( currentLoadedMusic,0,pan, 0,gLooping,instance)             
        tuneVolume = 0
        

###########################################
# PlaySound
#Wrapper for PC.PlaySound
def playSound( Sound,volume,panning,pitch):
    PC.playSound( WAV_Resources[Sound],volume,panning-1, pitch)

def stopTune():
    PC.stopTune()
###########################################
# PlaySound
#Wrapper for PC.PlaySound which takes a list of alternate sounds and picks one
def playSimpleSoundList( SoundList,panning=0,volume = 1):
    if(SoundList != None):
        index = random.randint(1,len(SoundList))
        if SoundList[index-1] != None:
            PC.playSound( WAV_Resources[SoundList[index-1]],profiles[currentProfile].soundVolume/4.0*volume,panning,0)

def playSimpleSoundDistance( Sound,soundX):
    if(Sound != None):
        middleScreen =  cameraX+400
        attenuation = soundX- middleScreen
        if attenuation <0:
            attenuation *=-1
        attenuation = 500 - attenuation
        if attenuation>0:
            attenuation /= 800.0
            PC.playSound( WAV_Resources[Sound],attenuation*profiles[currentProfile].soundVolume/4.0,0,0)
                

def playMusicSimple(Sound,tuneVolume = 1):
    if Sound != None:
        MusicVolume = profiles[currentProfile].musicVolume/4.0 * tuneVolume
        PC.playSound( WAV_Resources[Sound],MusicVolume,0,0)

def playSimpleSound( Sound,volume = 1,panning=0,pitch= 0):
    if(Sound != None):
        PC.playSound( WAV_Resources[Sound],(profiles[currentProfile].soundVolume/4.0)*volume,0,pitch)

        ###########################################
# MouseWheel
#
# Mouse Wheel handling. Called on wheel turn.
# Parameter is wheel direction.
#
###########################################
def mouseWheel(delta):
    #import copy
    global mouseWheelPos
    global mouseDelta
    global editorScrollBar
    global editorScrolled
    editorScrolled = 1
    editorScrollBar += delta
    if editorScrollBar<0:
      editorScrollBar =0
    game.mouseWheel(delta)

    mouseDelta = delta
    mouseWheelPos += delta
###########################################
# keydown
#
# Key handling. Called on keypress.
# Parameter is key code.
#
###########################################
def keydown( key ):
        global downKey
	#print "keydown called with", key
        global keyArray
        #print(key)
        if(key>0 and key <512):
            keyArray[key] = 1
        if(key>0 and key <255):
            workingString.addChar(key)
        downKey=key
###########################################
# keyup
#
# Key handling. Called on key release.
# Parameter is key code.
#
###########################################
def keyup( key ):
        global keyArray
      
        if(key>0 and key <512):
            keyArray[key] = 0
            keyRepeatArray[key] = 0
###########################################
# exitGame
#
# Return non-zero if game should terminate 
#
###########################################
def checkKey(key):
    global keyRepeatArray
    if(keyArray[key] == 1):
        keyRepeatArray[key] = 1   
        return 1
    return 0
    
def checkKeyNoRepeat(key):
    global keyRepeatArray
    if(keyArray[key] == 1 and keyRepeatArray[key] == 0):
        keyRepeatArray[key] = 1   
        return 1
    return 0

def checkKeyUp(key):
    if keyArray[key] == 0: 
        return 1
    return 0

def noKeyDown():
    for key in keyArray:
        if key != 0:
            return 0
    return 1

def anyKeyDown():
    found = 0
    for key in keyArray:
        if key != 0:
            keyRepeatArray[key] = 1
            found = 1
    return found

def exitGame(): 
	return doExit;
 
def doInstructions(delta):
    global thisLevelTutioral
    if levelMetaData.Instructions:
        if globalPlayer:
            if tutorialsOn and arcadeMode == 0 and thisLevelTutioral==0 and globalPlayer.PlatformOn:
                thisLevelTutioral += 1
                instructionManager.showInstruction(levelMetaData.Instructions)  
                setLevelAttempted(levelNumber)      
# update
#
# Basic tick function. Parameter is a time
# delta.
#
###########################################

def update( delta ):
	# call the draw function
	PC.markDirty()
	global time
        global inEditor
        global lives
        global score
        global tempDelta
        global gamePaused
        global totalTimePlayed
        global displayScore
        global startLevelTimer
        global  levelTime
        global gameOver
        global continousTime
        global oldCameraX
        global double1DownCount
        global double2DownCount
        global smartBombCount
        global globalOldPlatformOn
        global oldCameraX
        global gameLife
        gameLife += delta
        tuneTick(delta)
        if double1DownCount>0:
            double1DownCount -= delta
            if double1DownCount<0:
                double1DownCount = 0
                globalOldPlatformOn = None
        if double2DownCount>0:
            double2DownCount -= delta
            if double2DownCount<0:
                double2DownCount = 0
                globalOldPlatformOn = None
        oldCameraX = cameraX
        tickCursors(delta)
        continousTime += delta
        instructionManager.tick(delta)
        particleController.tick(delta)

        fadeManager.tick(delta)


        if(dataIsLoaded==0):
            loadResources(delta)
        else:
            if(gamePaused or forcePause or escapeMenu.active):
                delta = 0
                if escapeMenu.active:
                    escapeMenu.tick(delta)
            time += delta
            tempDelta = delta+1
            ScreenMessages.tickMessages(delta)
            PC.showMouse(cursorEnabled)
            if(metaGame):
                StartGameTick(delta)
            else:
                game.tick(delta)

def RenderObjects():
    global objects
    #pass 0
    for thisObject in objects:
            thisObject.render()
########################################
# TickObjects
#
# Loops through all the objects in the list ticking them
#
###########################################

def tickObjects(delta):
    global objects
    global solidObjects

    for thisObject in objects:
        thisObject.tick(delta)  

###########################################
# draw
#
# Basic draw function. Make all render
# calls from here and here alone.
#
###########################################
def draw():
        global objects
	# draw some stuff
	#import PycapRes
        global time
        global resx
        global resy 
        global fontx
        global fonty
        global rotation
        if(dataIsLoaded==0):
            renderLoadingScreen()
        else:
 
            renderGame()

        fadeManager.render()
copyRightMessage = ScreenMessage()
doNoDistribute = ScreenMessage()
Demo = ScreenMessage()

startLogoFade = 450
logoCount = startLogoFade - 50
pubLogoCount = startLogoFade

def renderpubLogo():
    x = 0
    y = 0
   # import PycapRes
    if showNonFreeLogos:
        PC.drawImage( pubLogo ,0, 0)
    else:
        PC.setFont( font36 )
        drawStringDropShadow("Tweeler presents....",200,300,255,255,255)         
    fadeAlpha = (150-pubLogoCount)*3
    if pubLogoCount>startLogoFade-300:
        fadeAlpha = (300-(startLogoFade-pubLogoCount))
    if fadeAlpha>255:
        fadeAlpha = 255
    if fadeAlpha>0:
        if fadeAlpha > 255:
            fadeAlpha = 255
        PC.setColourize(1)
        PC.setColour(0,0,0,fadeAlpha)
        PC.fillRect( 0,0,800,600)
        PC.setColourize(0)
    
startLogoFade = 500
logoCount = startLogoFade

def renderLogo():
    x = 100
    y = 50
    #import PycapRes
    if showNonFreeLogos:
        PC.drawImage( logoBack ,0, 0)
        PC.drawImage( logoScreen ,x, y)
        angle = (logoCount+250-startLogoFade)/300.0
        if (int(logoCount)%40)<20:
            logoText = logoText1
        else:
            logoText = logoText2
        PC.drawImageRot( logoText,x, y,angle) 
    else:
        PC.setFont( font36 )
        drawStringDropShadow("A Charlie Dog Games Production",75,300,255,255,255)         
    fadeAlpha = (150-logoCount)*3
    if logoCount>startLogoFade-300:
        fadeAlpha = (300-(startLogoFade-logoCount))
    if fadeAlpha>255:
        fadeAlpha = 255
    if fadeAlpha>0:
        if fadeAlpha > 255:
            fadeAlpha = 255
        PC.setColourize(1)
        PC.setColour(0,0,0,fadeAlpha)
        PC.fillRect( 0,0,800,600)
        PC.setColourize(0)
    
def tickLogo(delta):
    global logoCount
    logoCount -= delta
    if showAllLogo==0:
        logoCount = 0
    
def tickpubLogo(delta):
    global pubLogoCount
    pubLogoCount -= delta
    if showAllLogo==0:
        pubLogoCount = 0   
    
loadAlpha = 255

def tickLoading(delta):
    global loadAlpha
    loadAlpha -= delta*4
    if loadAlpha < 0:
        loadAlpha = 0

def renderLoadingScreen():
    if pubLogoCount > 0:
        renderpubLogo()
        return

    if logoCount > 0:
        renderLogo()
        return
      
    message = messages.Loading
    tabY = 410
    PC.drawmodeNormal()
    PC.setColour(24,0,80,32 )

    #copyRightMessage.RenderMessage()
    Demo.RenderMessage()
    doNoDistribute.RenderMessage()
    LoadingBarX = 10
    fraction = 1
    barLength = 240
    if(len(allGraphicFilesNames)!=0):
        fraction = (fileIndex)/float(len(allGraphicFilesNames))
#    JakePos = LoadingBarX+ (fraction*barLength)
    x = 50
    y = 500
  #  starSize  = 75
 #   leftRect = LoadingBarX - 5
 #   length =  barLength + starSize + 5 
 #   topRect = y-5
 #   height= starSize + 5
 #   PC.setColour(0,0,0,128)
 #   PC.fillRect(leftRect,topRect,length,height)
   
    rot = fraction
    rot *= 44/(7.0)
    x1 = x + fraction * 200
    y1 = y
    PC.drawImageRot( loadingBar,x1, y1, rot)
    alpha = loadAlpha
    if alpha>0:
        if alpha > 255:
            alpha = 255
        PC.setColourize(1)
        PC.setColour(0,0,0,alpha)
        PC.fillRect( 0,0,800,600)
        PC.setColourize(0)
    
def renderGame():
    if(metaGame):
        StartGameDraw()
    else:
        game.render()
    instructionManager.render()
    ScreenMessages.RenderMessages()
    particleController.render()
    renderCursors() 
    if mouseOverMessage != None:
        if mouseOverMessage.function!=None:
            mouseOverMessage.function(mouseOverMessage.parameter)
        mouseOverMessage.function=None
                  
class EscapeMenuClass:
    active = 0
    def tick(self,delta):
        if self.active:
            if checkKeyNoRepeat(keyMap.escapeKey.keyValue):
                returnToStoryEscape()
       
    def render(self):
        if self.active:
            return 0
        
    def toggle(self):
        if self.active:
            self.active = 0
            ScreenMessages.clearMessages()
        else:
            if self.active == 0:
                setTargetVolume(quietMusic)
            ScreenMessages.clearMessages()
            self.active = 1
            setLevelAttempted(levelNumber) 
            x = 250
            y = 200
            ScreenMessages.setMessageStatic(messages.Paused,None,-1,y,None,None) 
            y += 80
            ScreenMessages.setMessageStatic(messages.ResumeLevel,None,x,y,resumeLevel,None) 
            if arcadeMode == 0:
                y += 60
                ScreenMessages.setMessageStatic(messages.RestartLevel,None,x,y,setUpReplayLevel,None) 
            y += 60
            ScreenMessages.setMessageStatic(messages.QuitLevel,None,x,y,returnToStoryEscape,None)   
            
escapeMenu = EscapeMenuClass()

class GameOverMenuClass:
    active = 0
    def tick(self,delta):
        return 0
       
    def render(self):
        return 0
        
    def startMessages(self):
        global oldMetaGame  
        if highScoreCanvas.newHighScore(score)!= -1 and arcadeMode ==1:
            fadeManager.fadeDown(menuItems.highScoreCanvas)
            oldMetaGame = 0 
            escapeMenu.active = 0
            return
        y = 260
        x = 220
        ScreenMessages.setMessageStatic(messages.RestartLevel,None,x,y,gameOverRestartLevel,None) 
        y += 60
        if arcadeMode:
            ScreenMessages.setMessageStatic(messages.QuitLevel,None,x,y,returnToStory,None) 
        else:
            ScreenMessages.setMessageStatic(messages.ContinueStory,None,x,y,returnToStory,None)
            
gameOverMenu = GameOverMenuClass()

def doHighScoreMenu():
    global oldMetaGame
    oldMetaGame = 0 
    fadeManager.fadeDown(menuItems.highScoreCanvas)
    #startGame = 1
    escapeMenu.active = 0
    
def StartGameTick(delta):
        global startGame
        global canStart
        if metaGame >=1:
            menuClasses[metaGame].tick(delta)
            cheatCanvas.checkActivation(delta)
            
class Score:
    name = ''
    score = 0
    time = 0
    
InitialScores = [
    ['CharlieDog',6000000,0],
    ['Grace',5000000,0],
    ['Farbs',4000000,0],
    ['Joseph',3000000,0],
    ['Simon',2000000,0],
    ['Victoria',1000000,0],
    ['Gillie',400000,0],
    ['BillyRIP',200000,0],
    ['Ed',100000,0],
    ['Thomas',50000,0],
]
   
class canvas:
    life = 0
    animationSwitch =20
    frameNumber = 0
    life = 0
    animation= animationSets.splash_screen1
    backdrop = "menu_background"
    frame = None
    title = None
    titleY = -100
    titleRotation = 0.1
    titleTargetY = 10
    titleSpeed = 0
    targetRotation = 0.1
    frame1X = 20
    frame1Y = 330
    frame2X= 780
    frame2Y = 330
    frameScale = 1
    overlay = None
    character = ""
    characterX = 20
    characterY = 150
    
    def controllerButtons(self):
        buttons = getController(6)
        self.leftShoulder = buttons & 256
        self.rightShoulder = buttons & 512
        self.AButton = buttons & 4096
        self.BButton = buttons & 8192
        self.upButton = buttons & 1
        self.downButton = buttons & 2
        self.leftButton = buttons & 4
        self.rightButton = buttons & 8
        self.backButton = buttons & 32
        self.startButton = buttons & 16
    
    def ressetTitle(self):
        self.titleY = -300
        self.titleRotation = 0.4
        self.titleTargetY = 10
        self.titleSpeed = 0
        self.targetRotation = 0.1    
 
    def tick(self,delta):
        if metaGame != oldMetaGame:
            fadeManager.fadeUp()
        self.life += delta
        self.animationSwitch -= delta;
        if(self.animationSwitch<= 0):
            self.frameNumber = self.animation[self.frameNumber][1]
            self.animationSwitch = self.animation[self.frameNumber][2]
        
        if(self.title != None):
            self.titleSpeed += 0.7
            self.titleY += self.titleSpeed
            if(self.titleRotation<self.targetRotation):
                self.titleRotation += 0.01
                if(self.titleRotation>self.targetRotation):
                    self.titleRotation=self.targetRotation
            if(self.titleRotation>self.targetRotation):
                self.titleRotation -= 0.01
                if(self.titleRotation<self.targetRotation):
                    self.titleRotation=self.targetRotation            
            if(self.titleY >self.titleTargetY):
                self.targetRotation = self.titleRotation * -0.8
                if(self.titleSpeed>.5):
                    self.titleSpeed *= -0.6
                else:
                    self.titleSpeed = 0
                self.titleY = self.titleTargetY
        
    def render(self):
        PC.setColourize(1)
        PC.setColour(255,255,255,32 )
        if self.backdrop:
            graphic = JPG_Resources[self.backdrop]    #main bac
            PC.drawImage( graphic, 0, 0)
        PC.setColour(255,255,255,255 )
        PC.setColourize(0)
        PC.drawmodeNormal()
        if(self.title != None):
            width = PCR.imageWidth(self.title)
            if self.titleRotation>0:
                rotation = self.titleRotation
            else:
                rotation = (44/7) + self.titleRotation
            PC.drawImageRot( self.title, (800-width)/2, self.titleY,self.titleRotation) 
        if(self.frame != None):
            width = PCR.imageWidth(self.frame)
            height = PCR.imageHeight(self.frame)
            if(self.frame1X != -1):
                PC.drawImageScaled( self.frame, self.frame1X, self.frame1Y,width*self.frameScale,height*self.frameScale)
            if(self.frame2X != -1):
               PC.drawImageScaled( self.frame, self.frame2X-width, self.frame2Y,width,height)
        self.renderCharacter()   

    def renderCharacter(self):
        if self.character:
            graphic = JPG_Resources[self.character]    #main bac
            PC.drawImage( graphic, self.characterX, self.characterY)        

    def mouseClick(self,button):
        return 0

class HighScores(canvas):
    scores = []
    pope = 0
    x=0
    y=0
    cameFromLevel = 0
    backdrop = "main_background"
    def initialiseScores(self):
        self.scores = []
        thisScore = None
        thisScore =  PC.readReg("HighScore")
        if(thisScore):
        #    print("Loading scores from registry")
            while(len(thisScore)>2):
                newScore = Score()
                dividor = thisScore.find('\n')
                newScore.name = thisScore[:dividor]
                thisScore = thisScore[dividor+1:]
                dividor  = thisScore.find('\n')
                newScore.score = int(thisScore[:dividor])
                thisScore = thisScore[dividor+1 :]
                dividor  = thisScore.find('\n')
                newScore.time = int(thisScore[:dividor])
                thisScore = thisScore[dividor+1 :]
                self.scores.append(newScore)
        else:
     #     print("Loading scores from default")
          for score in InitialScores:
              newScore = Score()
              newScore.name = score[0]
              newScore.score = score[1]
              newScore.time=score[2]
              self.scores.append(newScore)
    def writeScores(self):
        concatenatedScore = ""
        for score in self.scores:
            concatenatedScore = concatenatedScore+str(score.name)+'\n'+str(int(score.score))+'\n'+str(int(score.time))+'\n'
        if(PC.writeReg( "HighScore", concatenatedScore )):
            print("wrote score to registry")            
    
    def displayScores(self):
        index =0
        x = self.x
        for score in self.scores:

            if(index != scorePos):
                PC.setColour( 255-(index*10), 150+(index*10),0,255 )
                PC.setFont( font26 )
                PC.drawString(score.name, x, self.y )
            else:
                PC.setColour( 255,0,0,255)
                PC.setFont( font26 )
                PC.drawString(str(workingString.getDisplayString()),x, self.y )
            scoreString = numberToString(score.score)
            PC.drawString(scoreString, x+200, self.y )
            self.y = self.y + 40
            index += 1
            
    def tryInsert(self,thisscore,doInsert=1):
        index = 0
        for score in self.scores:
            if(thisscore>score.score):
                if doInsert:
                    global scorePos
                    tail = self.scores[index:]
                    head = self.scores[:index]
                    newScore = Score()
                    newScore.score=thisscore
                    newScore.name = ''
                    newScore.time = int(totalTimePlayed/100)
                    head.append(newScore)
                    self.scores = head+tail 
                    self.scores.pop() 
                    scorePos = index                   
                return index
            index+=1
        return -1
    def setName(self):
        if(scorePos>=0 and scorePos < len(self.scores)):
            self.scores[scorePos].name = workingString.thisString
    
    def newHighScore(self,thisscore):
        index = 0
        for score in self.scores:
            if(thisscore>score.score):
           #     print "high score",thisscore,score.score
                return index
            index+=1
        return -1
        
    def render(self):
        self.frame1X = -1
        self.frame2Y = 250
        canvas.render(self)
        self.x = 250
        self.y = 100
        self.displayScores()
        
    def tick(self,delta):    
        global metaGame
        global oldMetaGame
        global scorePos
        canvas.tick(self,delta)
        self.life += delta
        if(oldMetaGame!= metaGame):
            ScreenMessages.clearMessages()
            workingString.clearString()
            workingString.length = 9
            scorePos=self.tryInsert(game.tempScore)
            oldMetaGame = metaGame
            y = 500
            x = 260
            if scorePos == -1: 
                if self.cameFromLevel:              
                    ScreenMessages.setMessageStatic(messages.RestartLevel,None,-1,y,gameOverRestartLevel,None) 
                y += 50
                x += 10                
                ScreenMessages.setMessageStatic(messages.returnMenu,None,-1,y,backtoMainScreen)
            else:
                ScreenMessages.setMessageStatic(messages.NewHighScoreMenu,None,-1,540,None) 
                ScreenMessages.setMessageStatic(messages.EnterName,None,-1,590,None) 
            canvas.ressetTitle(self)
        if(checkKeyNoRepeat(keyMap.escapeKey.keyValue)):
            scorePos = -1
            backtoMainScreen()
            
        if(checkKeyNoRepeat(keyMap.enterKey.keyValue)):
            if scorePos >= 0:
                self.setName()
                ScreenMessages.clearMessages()
                y = 500
                x = 240
                if self.cameFromLevel:  
                    ScreenMessages.setMessageStatic(messages.RestartLevel,None,-1,y,gameOverRestartLevel,None) 
                y += 50
                x += 10                
                ScreenMessages.setMessageStatic(messages.returnMenu,None,-1,y,backtoMainScreen)
                scorePos = -1
                ressetScore(0)
            else:
                scorePos = -1
                backtoMainScreen()                
            
highScoreCanvas = HighScores() 

def ressetScore(newScore=0):
    global score
    global nextLifeScoreTarget
#   newScore = 2499999
    score = newScore
    nextLifeScoreTarget = 5000
    
def ressetLives(newLives=startLives):
    global lives
    lives = newLives
    


        
class mainScreen(canvas):
    dudeShadowAlpha = 0
    backdrop = "menu_background"
    poem = poem.poem1

    def render(self):
#        PC.setColour( 40, 220, 0, 255 )
#        PC.setFont( font36 )
#        name = self.animation[self.frameNumber][0]
        
        self.frame1X = -1
        self.frame2X = 770
        self.frame2Y = 280
        canvas.render(self)
        #currentPoem.render()
        self.renderButtons()
        
    def renderButtons(self):    
        upColour = [210, 190, 255, 128]
        overColour = [255, 210, 255, 255]
        x = 300
        y = 220
        spacing = 60
        renderButtonWithText("PlayButton",x,y,"main_button_over",None,"Play",font26,upColour,overColour)
        y += spacing
        renderButtonWithText("HighScoreButton",x,y,"main_button_over",None,"High Scores",font26,upColour,overColour)
        y += spacing        
        renderButtonWithText("OptionsButton",x,y,"main_button_over",None,"OPTIONS",font26,upColour,overColour)
        y += spacing
        renderButtonWithText("CreditButton",x,y,"main_button_over",None,"CREDITS",font26,upColour,overColour)
        y += spacing
#        renderButtonWithText("PlayerButton",420,380,"main_button_over",None,"PLAYER",font26,upColour,overColour)   
        player = profiles[currentProfile].playerName        
        renderButtonWithText("QuitButton",x,y,"main_button_over",None,"QUIT",font26,upColour,overColour)

        renderButtonWithText("WebSite",x,540,"main_button_over",None,"WWW.CharlieDogGames.com",font16,upColour,overColour)
        PC.drawmodeNormal()        
    def mouseClick(self,button):
        if button == 0:
            if clickOnButton("QuitButton"):
                exitGameOption()
            if clickOnButton("PlayButton"):
                selectCasual()      
            if clickOnButton("CreditButton"):
                doCredits()
            if clickOnButton("OptionsButton"):
                selectOptions()  
            if clickOnButton("PlayerButton"):
                changeProfile()  
            if clickOnButton("HighScoreButton"):
                game.tempScore = 0
                selectHighScore()  
            if clickOnButton("WebSite"):
                openWebPage("http://charliedoggames.com")  
                
    def tick(self,delta):
        global startGame
        global canStart
        global metaGame
        global oldMetaGame
        global score
        global lives
        global newGame
        global mouseEnabled
        global inGUI
        global firstTimeMainScreen
        global gameOver
        canvas.tick(self,delta)
        if(metaGame != oldMetaGame):
            self.masterDudeVolume = 1.2
            currentPoem.setUp()
            currentPoem.go = 1000
            game.running = 0
            fairyPointer.enabled = 1
            #playTune("MainScreen")
            if currentTunePlaying != levelData.menuSong:
                playTuneOgg(levelData.menuSong,1)
            inGUI = 1
            oldMetaGame = metaGame
            ScreenMessages.clearMessages()
            #ScreenMessages.setMessageStatic(messages.CharlieWeb,None,-1,595,launchCharlie) 
            if cheatCanvas.active:
                startX=70
                StartY=440
                YStep = 40
                ScreenMessages.setMessageStatic(messages.Cheats,None,startX,StartY,selectCheats) 
                StartY += YStep                
                ScreenMessages.setMessageStatic(messages.Action,None,startX,StartY,selectAction) 
                StartY += YStep
                ScreenMessages.setMessageStatic(messages.Puzzle,None,startX,StartY,selectPuzzle) 
                StartY += YStep
                ScreenMessages.setMessageStatic(messages.HighScore,None,startX,StartY,selectHighScore)
            mouseEnabled = 1
            canvas.ressetTitle(self)
        else:
            self.checkController()
            #currentPoem.tick(delta)
    
    def checkController(self):
        canvas.controllerButtons(self)
        if self.startButton or checkKeyNoRepeat(keyMap.spaceKey.keyValue) or  checkKeyNoRepeat(keyMap.enterKey.keyValue):
  #          profiles[currentProfile].inputMode = 0 #for controller control
            selectCasual()
              
        
        


mainScreenCanvas = mainScreen()
  
class WelcomeScreen(canvas):
    def render(self):
        self.frame1X = -1
        self.frame2X = 790
        self.frame2Y = 320
        PC.setColour( 40, 220, 0, 255 )
        PC.setFont( font36 )
        name = self.animation[self.frameNumber][0]
        self.frame = JPG_Resources[name]
        self.title = JPG_Resources["Title"]
        canvas.render(self)
            
    def tick(self,delta):
        global startGame
        global canStart
        global metaGame
        global oldMetaGame
        global score
        global lives
        global newGame
        global mouseEnabled
        global inGUI
        global firstTimeMainScreen
        global gameOver
        canvas.tick(self,delta)
        if(metaGame != oldMetaGame):
            inGUI = 1
            oldMetaGame = metaGame
            ScreenMessages.clearMessages()
            x = -1
            ScreenMessages.setMessageStatic(messages.Welcome,None,x,240,None,profiles[currentProfile].playerName+"!")
            x = -1
            ScreenMessages.setMessageStatic(messages.WelcomeInstructions1,None,x,290,None) 
            ScreenMessages.setMessageStatic(messages.WelcomeInstructions2,None,x,330,None) 
            ScreenMessages.setMessageStatic(messages.WelcomeInstructions3,None,x,370,None) 
            ScreenMessages.setMessageStatic(messages.WelcomeStory,None,270,480,selectStory) 
            ScreenMessages.setMessageStatic(messages.WelcomeMainMenu,None,270,530,backtoMainScreen)        
            mouseEnabled = 1
            canvas.ressetTitle(self)


welcomeCanvas = WelcomeScreen()
copywrite2 = "all game code is copywrite Charlie Dog Games August 2006"  
class CheatScreen(canvas):
    AllLevelOn = 0
    AllPowerOn = 0
    ScaleUpOn = 0
    active = 0
    def render(self):
        PC.setColour( 40, 220, 0, 255 )
        PC.setFont( font36 )
        self.title = JPG_Resources["Title"]
        canvas.render(self)
            
    def tick(self,delta):
        global startGame
        global canStart
        global metaGame
        global oldMetaGame
        global score
        global lives
        global newGame
        global mouseEnabled
        global inGUI
        global firstTimeMainScreen
        global gameOver
        canvas.tick(self,delta)
        if(metaGame != oldMetaGame):
            inGUI = 1
            oldMetaGame = metaGame
            ScreenMessages.clearMessages()
            ScreenMessages.setMessageStatic(messages.CheatTitle,None,-1,280,None) 
            y = 280
#            if self.AllLevelOn:
#                ScreenMessages.setMessageStatic(messages.AllLevelOn,None,-1,y,self.AllLevelCheat) 
#            else:
#                ScreenMessages.setMessageStatic(messages.AllLevelOff,None,-1,y,self.AllLevelCheat)

            
            ScreenMessages.setMessageStatic(messages.WelcomeMainMenu,None,-1,580,backtoMainScreen)        
            mouseEnabled = 1
            canvas.ressetTitle(self)
            
    def checkActivation(self,delta):
        global oldMetaGame
        if ((checkKey(keyMap.leftControlKey.keyValue) or checkKey(keyMap.rightControlKey.keyValue) ) and showAllLogo == 0):
            if checkKeyNoRepeat(keyMap.cheatKey.keyValue) and cheatsActive:
                oldMetaGame = -1
                if self.active == 0:
                    self.active = 1
                else: 
                    self.active = 0
            
    def AllLevelCheat(self):
        global oldMetaGame
        oldMetaGame= -1
        if self.AllLevelOn == 0:
            self.AllLevelOn = 1
        else:
            self.AllLevelOn = 0
            
    def scaleCheat(self):
        global oldMetaGame
        oldMetaGame= -1
        if self.ScaleUpOn == 0:
            self.ScaleUpOn = 1
        else:
            self.ScaleUpOn = 0
            
    def AllPowerCheat(self):
        global oldMetaGame
        oldMetaGame= -1
        if self.AllPowerOn == 0:
            self.AllPowerOn = 1
        else:
            self.AllPowerOn = 0
            
        
            
cheatCanvas = CheatScreen()

  

class gameOverScreen(canvas):
    enteringName = 0
    active = 0
    backdrop = None
    animation = animationSets.sad_jake
    frameYOffset = 0
    time = 0
  
    def render(self):
        self.overlay = None
        self.frame2X = -1
        self.frame1X = 270
        self.frameYFinish = 330
        self.titleTargetY = 20
        yOffset = (self.time*10) - 300
        if yOffset < self.frameYFinish:
            self.frame1Y = yOffset
        else:
            self.frame1Y =  self.frameYFinish + math.sin(self.time/7.5)*5
        name = self.animation[self.frameNumber][0]
        self.frame = JPG_Resources[name]
        self.title = JPG_Resources["GameOver"]
        canvas.render(self) 
        
    def tick(self,delta):
        global startGame
        global canStart
        global metaGame
        global oldMetaGame
        global score
        global lives
        global newGame
        global mouseEnabled
        global inGUI
        global firstTimeMainScreen
        global gameOver
        canvas.tick(self,delta)
        self.time += delta

    def makeActive(self):
        canvas.ressetTitle(self)
        self.active = 1
        self.time = 0
            
gameOverCanvas = gameOverScreen()    

class nameScreen(canvas):
    enteringName = 0
  
    def render(self):
#        self.overlay = JPG_Resources["MenuMask"]
        self.frame1X = -1
        self.frame2X = 770
        self.frame2Y = 300
        if(profiles[currentProfile].playerName != "Empty"):
            return
        PC.setColour( 40, 220, 0, 255 )
        PC.setFont( font36 )
        name = self.animation[self.frameNumber][0]
        self.frame = JPG_Resources[name]
        self.title = JPG_Resources["Title"]
        canvas.render(self) 
        if(self.enteringName):
            PC.drawmodeNormal() 
            PC.setColour( 40, 220, 0, 255 )
            PC.setColourize(1)
            PC.setFont( font36 )
            PC.drawString(str(workingString.getDisplayString()), 300, 380 )
        #canvas.render(self) 
        
    def tick(self,delta):
        global startGame
        global canStart
        global metaGame
        global oldMetaGame
        global score
        global lives
        global newGame
        global mouseEnabled
        global inGUI
        global firstTimeMainScreen
        global gameOver
        canvas.tick(self,delta)
        if(metaGame != oldMetaGame):
            playTuneOgg(levelData.menuSong,1)
            inGUI = 1
            fairyPointer.enabled = 0
            workingString.clearString()
            workingString.length = 9
            oldMetaGame = metaGame
            ScreenMessages.clearMessages()
            if(profiles[currentProfile].playerName == "Empty"):
              #  ScreenMessages.setMessageStatic(messages.Welcome,None,-1,250,None)
                ScreenMessages.setMessageStatic(messages.EnterName,None,-1,250,None)
                ScreenMessages.setMessageStatic(messages.PressEnter,None,-1,300,None)
                self.enteringName = 1
            else:
                self.enteringName = 0
                exitNameSelection(0)    
            mouseEnabled = 1
            canvas.ressetTitle(self)
        if checkKey(keyMap.enterKey.keyValue):
            profiles[currentProfile].playerName = workingString.thisString
            self.enteringName = 0
            exitNameSelection(1)
            fairyPointer.enabled = 1
            
nameCanvas = nameScreen()    

def changeProfile():
    global metaGame
    fadeManager.fadeDown(menuItems.profileCanvas)
    nextAvailableProfile=0

class profileScreen(canvas):
    enteringName = 0
    y = 0
    stringEnterY=0
    deletingName = 0   
  
    def render(self):
        self.frame1X = -1
        PC.setColour( 255, 220, 255, 255 )
        PC.setFont( font36 )
        canvas.render(self)
        if(self.enteringName):
            PC.setFont( font30)
            PC.setColour( 255, 255, 255, 255 )
            PC.drawString(str(workingString.getDisplayString()), 540, self.stringEnterY )
       
    def tick(self,delta):
        global startGame
        global canStart
        global metaGame
        global oldMetaGame
        global score
        global lives
        global newGame
        global mouseEnabled
        global inGUI
        global firstTimeMainScreen
        global gameOver
        global currentProfile
        canvas.tick(self,delta)
        if(metaGame != oldMetaGame):
            inGUI = 1
            workingString.clearString()
            workingString.length = 9
            oldMetaGame = metaGame
            ScreenMessages.clearMessages()
            index = 0
            self.nextAvailableProfile = -1
            self.y = 250
            profileIdx = 0
            baseX = -1
            selectedName = None
            activeProfiles = 0
            for profile in profiles:
                if(profile.playerName != "Empty"):
                    x = baseX
                    activeProfiles += 1
                    if(index==currentProfile):
                        ScreenMessages.setMessageStatic(messages.ProfileS,None,x,self.y,selectProfile,profile.playerName,index)
                        selectedName = profile.playerName +" ?"
                    else:
                        ScreenMessages.setMessageStatic(messages.ProfileNS,None,x,self.y,selectProfile,profile.playerName,index) 
                    self.y +=40
                else:
                    self.nextAvailableProfile = index
                index += 1
            if self.nextAvailableProfile != -1:
                if(self.enteringName):
                    ScreenMessages.setMessageStatic(messages.enterNameProfile,None,baseX,self.y,None)
                    self.stringEnterY = self.y
                else:  
                    ScreenMessages.setMessageStatic(messages.createProfile,None,baseX,self.y,newProfile,parameter=index)
            if self.enteringName==0:
                if self.deletingName == 0:
                    if activeProfiles > 1:
                        ScreenMessages.setMessageStatic(messages.deleteProfile,None,baseX,490,self.checkDelete,parameter=index) 
                    ScreenMessages.setMessageStatic(messages.returnMenu,None,-1,540,self.exitNameSelectionProfile) 
                else:
                    ScreenMessages.setMessageStatic(messages.confirmDeleteMessage,None,40,490,None,selectedName)
                    ScreenMessages.setMessageStatic(messages.confirmDelete,None,baseX,540,self.deleteProfile,parameter=index)
                    ScreenMessages.setMessageStatic(messages.cancelDelete,None,baseX,580,self.cancelDelete,parameter=index)                    
            mouseEnabled = 1
            canvas.ressetTitle(self)
        if self.enteringName:
            if checkKey(keyMap.enterKey.keyValue):
                if self.nextAvailableProfile != -1:
                    currentProfile = self.nextAvailableProfile
                    profiles[currentProfile].ressetProfile()
                    profiles[currentProfile].playerName = str(workingString.thisString)
                    self.enteringName = 0
                    oldMetaGame = 0 #force refresh
                    
    def exitNameSelectionProfile(self):
        global metaGame
        if(self.enteringName==0):
            exitProfile()  

    def deleteProfile(self,index):
        global oldMetaGame
        global currentProfile
        occupied = 0
        index = 0
        #need to make sure there is at least two slots occupied so we can delete one
        for profile in profiles:
            if profile.playerName != "Empty":
                occupied += 1
        if(occupied >1):
            #resset the selected profile
            profiles[currentProfile].ressetProfile()
            #now find the first occupied profile so we can reset the current profile
            index = 0
            for profile in profiles:
                if profile.playerName != "Empty":
                    currentProfile = index
                    break
                index += 1
            oldMetaGame = 0 
            self.deletingName = 0
            
    def checkDelete(self,index):
        global oldMetaGame     
        oldMetaGame = 0   
        self.deletingName = 1
        
    def cancelDelete(self,index):
        global oldMetaGame     
        oldMetaGame = 0   
        self.deletingName = 0

profileCanvas = profileScreen()

def newProfile(index):
    global oldMetaGame
    profileCanvas.enteringName = 1
    oldMetaGame = 0 #force refres
    
 
def selectProfile(index):
    global currentProfile
    global oldMetaGame
    currentProfile = index
    oldMetaGame = 0

def exitNameSelection(first):
    global metaGame
    writeProfiles()
    PC.writeReg("CurrentProfile",str(currentProfile))
    fadeManager.fadeDown(menuItems.mainScreenCanvas)
        
def exitProfile():
    global metaGame
    writeProfiles()
    PC.writeReg("CurrentProfile",str(currentProfile))
    fadeManager.fadeDown(menuItems.mainScreenCanvas)

def doCredits():
    fadeManager.fadeDown(menuItems.creditCanvas)
    
def doInstructionScreen():
    fadeManager.fadeDown(menuItems.instructionListCanvas)
    
def exitGameOption():
	global doExit
	fadeManager.fadeDown(menuItems.sellUpExitCanvas)
    
def selectHighScore():
    global metaGame
    highScoreCanvas.cameFromLevel = 0
    fadeManager.fadeDown(menuItems.highScoreCanvas)
def selectCheats():
    global metaGame
    fadeManager.fadeDown(menuItems.cheatCanvas)  
    
def selectOptions():
    global metaGame
    fadeManager.fadeDown(menuItems.optionsCanvas)


def selectCasual():
    selectGame(0)

def selectAction():
    selectGame(1)
    
def selectSpeed(): #not used at the moment
    selectGame(2)
    
def selectPuzzle():
    selectGame(3)
  
def selectGame(Mode):  
    global startGame
    global metaGame
    global score
    global lives
    global newGame
    global mouseEnabled
    global inGUI
    global firstTimeMainScreen
    global gameOver 
    global arcadeMode 
    global speedMode
    global puzzleMode
    global levelNumber
    #Mode = 2
    arcadeMode = 0
    speedMode = 0
    puzzleMode = 0
    if Mode == 0:
        if profiles[currentProfile].casualLevel == 0:
            profiles[currentProfile].casualLevel = startLevel
            profiles[currentProfile].casualScore = 0
            profiles[currentProfile].casualLives = 3     
            fadeManager.fadeDown(menuItems.game,1)
        else:
            fadeManager.fadeDown(menuItems.continueCasualCanvas,1)
    if Mode == 1:
        arcadeMode = 1
        if profiles[currentProfile].actionLevel == 0:
            fadeManager.fadeDown(menuItems.game,1)
        else:
            fadeManager.fadeDown(menuItems.continueActionCanvas,1)
    if Mode == 3:
        puzzleMode = 1
        if profiles[currentProfile].getPuzzleElementValue(0,0):
            fadeManager.fadeDown(menuItems.continuePuzzleCanvas,1)
        else:
            fadeManager.fadeDown(menuItems.game,1)
            profiles[currentProfile].puzzleCollumn = 0
            profiles[currentProfile].puzzleRow = 0
            
def getKeyName(key):
    keyName = chr(key.keyValue)
    for namedKey in keyMap.namedKeys:
        if namedKey[0] == key.keyValue:
            keyName = namedKey[1]  
    return keyName

renderOptions = [messages.Low[0],messages.Med[0],messages.High[0]]

class optionsScreen(canvas):
    selectedOption = -1
    oldDownKey=0
    selectionReady = -1
    oldDownKey = -1
#    character = "char_penny"
#    characterX = 20
#    characterY = 150
    def showKeys(self):
        global fullScreenMode
        x = 270
        y = 200
        option = 0
        PC.setColour( 0, 0, 0, 40 ) 
        PC.fillRect(x-40,y-10,320,280)   
        PC.fillRect(x-45,y-15,330,290)           
        PC.setColour( 128, 45, 45, 255 )
        y += 30
        #PC.drawString(getWordFromNumber(int(profiles[currentProfile].soundVolume)),x+170,y) 
        y += 45
#        PC.drawString(getWordFromNumber(int(profiles[currentProfile].musicVolume)),x+170,y) 
        y += 45        
#        if(PC.getFullscreen()):
#            fullScreenMode = 1
#            PC.drawString("Full",x+170,y) 
#        else:
#            fullScreenMode = 0
#            PC.drawString("Window",x+170,y) 
        y += 45
#        if profiles[currentProfile].tutorials:
#            PC.drawString(messages.TutorialEnabled[0],x+170,y)
#        else:
#            PC.drawString(messages.TutorialDisabled[0],x+170,y)      
        y += 45
#        if PC.getIsAccelerated():
#            PC.drawString(messages.Enabled[0],x+170,y)
#        else:
#            PC.drawString(messages.Disabled[0],x+170,y) 
#        y += 45
#        PC.drawString(renderOptions[renderDetailLevel],x+170,y)
    def render(self):
 #       character = self.animation[self.frameNumber][0]
 ##       self.frame = JPG_Resources[ character]
 #       self.title = JPG_Resources[ 'Options']

        canvas.render(self)
#        self.showKeys()
        
    def tick(self,delta):    
        global metaGame
        global oldMetaGame
        global scorePos
        global score
        global inGUI
        canvas.tick(self,delta)
        maxOption = len(keyMap.configurableKeys)
        if(oldMetaGame!= metaGame):
            canvas.ressetTitle(self)
            inGUI = 1
            mouseEnabled = 1
            ScreenMessages.clearMessages()
            self.frame1X = -1
            self.frame2X = 770
            self.frame2Y = 280
            x = 280
            optionX = x+170
 #           ScreenMessages.setMessageStatic(messages.SelectOption,None,-1,160,None)  
 
            ScreenMessages.setMessageStatic(messages.returnMenu,None,x,500,backtoMainScreen)     
            
            y = 250
            string = getWordFromNumber(int(profiles[currentProfile].soundVolume))
            ScreenMessages.setMessageStatic(messages.SoundVolume,None,x,y,changeSoundVolume,string)
            
            y += 60           
            string = getWordFromNumber(int(profiles[currentProfile].musicVolume))
            ScreenMessages.setMessageStatic(messages.MusicVolume,None,x,y,changeMusicVolume,string)
             
            y += 60 
            if(PC.getFullscreen()):
                fullScreenMode = 1
                string = "Full" 
            else:
                fullScreenMode = 0
                string = "Window"
            ScreenMessages.setMessageStatic(messages.WindowMode,None,x,y,ToggleWindowed,string)
            
           # y += 40
           # if profiles[currentProfile].tutorials:
           #     string = "On"
           # else:
           #     string = "Off"   
           # ScreenMessages.setMessageStatic(messages.Tutorials,None,x,y,ToggleTutorials,string)
            
            y += 60           
            if PC.getIs3DAccelerated():
                string = "On"
            else:
                string = "Off"
#            ScreenMessages.setMessageStatic(messages.Acceleration,None,x,y,ToggleAcceleration,string)               
 #           y += 40
#            string = renderOptions[renderDetailLevel]
#            ScreenMessages.setMessageStatic(messages.DetailLevel,None,x,y,ToggleDetailLevel,string)
#            y += 40
#            if profiles[currentProfile].inputMode == 0:
 #               string = "Keyboard"
  #          elif profiles[currentProfile].inputMode == 1:
   #             string = "Mouse"
    #        else:
     #           string = "Controller"
      #      ScreenMessages.setMessageStatic(messages.controlMode,None,x,y,ToggleController,string)     
            oldMetaGame = metaGame
            checkKey(keyMap.escapeKey.keyValue) #make sure the no repeat flag is set
        if(checkKeyNoRepeat(keyMap.escapeKey.keyValue)):
            backtoMainScreen()
        if(self.selectedOption >= 0): 
            if(downKey != self.oldDownKey):
                keyMap.configurableKeys[self.selectedOption].keyValue = downKey
                self.selectedOption = -1
        self.oldDownKey=downKey
                
    def chooseSelection(self):
        self.selectedOption = ((mousey-210)/40)+1

def ToggleAcceleration():
    global oldMetaGame
    oldMetaGame = -1
    if PC.getIs3DAccelerated():
        PC.set3DAccelerated(0)
    else:
        PC.set3DAccelerated(1)
        
        
def ToggleController():
    global oldMetaGame
    oldMetaGame = -1
    if profiles[currentProfile].inputMode:
        profiles[currentProfile].inputMode = 0    
    else:
        profiles[currentProfile].inputMode = 1
        
def ToggleDetailLevel():
    global oldMetaGame
    oldMetaGame = -1
    global renderDetailLevel
    renderDetailLevel += 1
    if renderDetailLevel > 2:
        renderDetailLevel = 0

def ToggleTutorials():
    global oldMetaGame
    oldMetaGame = -1
    if profiles[currentProfile].tutorials: 
        profiles[currentProfile].tutorials = 0
    else:
        profiles[currentProfile].tutorials = 1
            

class creditScreen(canvas):
    exitFlag = 0    
#    character = "char_safari"
    characterX = 20
    characterY = 150
    def render(self):
        character = self.animation[self.frameNumber][0]
        self.frame = None

        canvas.render(self)
#        PC.setFont( font22 )  
        
    def tick(self,delta):    
        global metaGame
        global oldMetaGame
        global scorePos
        global score
        global inGUI
        canvas.tick(self,delta)
        if(oldMetaGame!= metaGame):
            ScreenMessages.clearMessages()
            canvas.ressetTitle(self)
            inGUI = 1
            mouseEnabled = 1
            y_delta = 25
            y = 150
#            ScreenMessages.setMessageStatic(messages.credit1,None,-1,y,None )
            y += 70
            ScreenMessages.setMessageStatic(messages.credit2,None,-1,y,None )
            y += y_delta
            ScreenMessages.setMessageStatic(messages.credit3,None,-1,y,None )
            y += y_delta
            ScreenMessages.setMessageStatic(messages.credit4,None,-1,y,None )
            y += y_delta
            ScreenMessages.setMessageStatic(messages.credit14,None,-1,y,None )
            y += y_delta
            ScreenMessages.setMessageStatic(messages.credit5,None,-1,y,None )
            y += y_delta
            ScreenMessages.setMessageStatic(messages.credit6,None,-1,y,None )
            y += y_delta
            ScreenMessages.setMessageStatic(messages.credit13,None,-1,y,None )
            y += y_delta+20
            ScreenMessages.setMessageStatic(messages.credit7,None,-1,y,None )
            y += y_delta
            ScreenMessages.setMessageStatic(messages.credit8,None,-1,y,None )
            y += y_delta
            ScreenMessages.setMessageStatic(messages.credit9,None,-1,y,None )
            y += y_delta
            ScreenMessages.setMessageStatic(messages.credit10,None,-1,y,None )
            y += y_delta
            ScreenMessages.setMessageStatic(messages.credit12,None,-1,y,None )
            y += y_delta
            ScreenMessages.setMessageStatic(messages.credit11,None,-1,y,None )            
            if self.exitFlag:
                ScreenMessages.setMessageStatic(messages.returnMenu,None,-1,590,self.exit) 
            else:
                ScreenMessages.setMessageStatic(messages.returnMenu,None,-1,590,self.exit) 
            x = 265
            y = 210
                 
            oldMetaGame = metaGame
            
    def buyGame(self):
        backtoMainScreen()
        
    def exit(self):
        backtoMainScreen()

creditCanvas = creditScreen()

class continuePuzzleScreen(canvas):
    exitFlag = 0   
    gridTop = 100
    gridLeft = 150
    gridHSpace = 50
    gridVSpace = 50
    elementWidth = 50
    elementHeight = 50
    life = 0
  
    
    def mouseClick(self,mdn):
        x = mousex - self.gridLeft
        x /= self.gridHSpace
        y = mousey - self.gridTop
        y /= self.gridHSpace  
        x = int(x)
        y = int(y)

        if y >= 0 and y < len(boardLayouts.puzzleGrid):
            collumn = game.puzzleGrid[y]
            if x >= 0 and x < len(collumn):
                if self.canBeClicked(x,y):
                    #print "continue puzzle screen",x,y,collumn,len(boardLayouts.puzzleGrid)
                    profiles[currentProfile].puzzleCollumn = x
                    profiles[currentProfile].puzzleRow = y
                    fadeManager.fadeDown(menuItems.game)
         
    def mouseOver(self,x,y,width,height):
        left = x
        right = x + self.elementWidth
        top = y
        bottom = y + height 
        if left < mousex and right > mousex and top < mousey and bottom > mousey:
            return 1
        else:
            return 0
            
    def canBeClicked(self,xIndex,yIndex):
        if cheatCanvas.active:
            return 1
        if profiles[currentProfile].getPuzzleElementValue(xIndex,yIndex):
            return 1
        if profiles[currentProfile].getPuzzleElementValue(xIndex-1,yIndex):
            return 1
        if profiles[currentProfile].getPuzzleElementValue(xIndex+1,yIndex):
            return 1
        if profiles[currentProfile].getPuzzleElementValue(xIndex,yIndex-1):
            return 1
        if profiles[currentProfile].getPuzzleElementValue(xIndex,yIndex+1):
            return 1
        return 0
            
    def checkHorizontalLine(self,yIndex):
        xIndex = 0
        row = game.puzzleGrid[yIndex]
        for element in row:
            if profiles[currentProfile].getPuzzleElementValue(xIndex,yIndex) == 0:
                return 0
            xIndex += 1
        return 1
            
    def render(self):

        character = self.animation[self.frameNumber][0]
        self.frame = None
        canvas.render(self)
        PC.setFont( font22 )  
        PC.setColourize(1)
        PC.drawmodeNormal()

        self.renderRowBears(1)
        self.renderRowBears(0)
        self.renderGrid(1)
        self.renderGrid(0)

    def renderGrid(self,shadow):
        y = self.gridTop
        if shadow:
            y += 4
        yIndex= 0
        PC.setColourize(1)
        for row in game.puzzleGrid:
            xIndex = 0
            x = self.gridLeft
            if shadow:
                x += 2
            for element in row:
                canBeClicked = self.canBeClicked(xIndex,yIndex)
                if profiles[currentProfile].getPuzzleElementValue(xIndex,yIndex):
                    PC.setColour(255,200,0,255)
                    resName = "TrophyBear"
                elif canBeClicked:
                    PC.setColour(255,255,255,255)
                    resName = "balloon_2"
                else:
                    resName = "balloon_4"
                    PC.setColour(50,50,50,50)
                res = JPG_Resources[ resName]
                screenX = x
                screenY= y
                if shadow:
                    PC.setColour(0,0,0,100)
                if shadow==0 or canBeClicked:
                    if canBeClicked:
                        screenY += math.sin((self.life+(x/1.1)+(y/1.3))/30.0)*3
                    PC.drawmodeNormal()
                    PC.drawImageScaled(res, screenX, screenY,self.elementWidth,self.elementHeight)
                    if self.mouseOver(x,y,self.elementWidth,self.elementHeight) and canBeClicked:
                        PC.drawImageScaled(res, screenX-4, screenY-4,self.elementWidth+8,self.elementHeight+8)     
                        PC.drawmodeAdd()
                        PC.drawImageScaled(res, screenX-4, screenY-4,self.elementWidth+8,self.elementHeight+8)                    
                PC.drawmodeNormal()
                x += self.gridHSpace
                xIndex += 1
            y += self.gridVSpace
            yIndex += 1
        PC.setColourize(0)
            
    def renderRowBears(self,shadow):  
        y = 0
        allComplete = 1
        PC.drawmodeNormal()
        for row in game.puzzleGrid:
            if self.checkHorizontalLine(y):
                width = 60
                height = 80
                PC.setColour(255,100,100,255)
                resName = "TrophyBear"
                res = JPG_Resources[ resName]
                offset = (y/2.0)
                screenY = self.gridTop + (offset* self.gridVSpace * 2)
                if y&1==0:
                    screenX = 60
                    screenX -= math.sin(self.life/50)*4
                else:
                    screenX = 740
                    screenX += math.sin(self.life/50)*4
                    width *= -1
                if shadow:
                    PC.setColour(0,0,0,80)
                    screenX += 3
                    screenY += 6
                PC.drawImageScaled(res, screenX,screenY, width,height)
            else:
                allComplete = 0

            y += 1
        if allComplete:
            PC.setColour(255,100,200,255)
            resName = "TrophyBear"
            res = JPG_Resources[ resName]
            screenY = 450
            screenX = 350
            screenY -= math.sin(self.life/50)*4
            rot = math.sin(self.life/40)/4.0
            if shadow:
                PC.setColour(0,0,0,80)
                screenX += 3
                screenY += 6
            PC.drawImageRot(res, screenX,screenY,rot)            
        
    def tick(self,delta):    
        global metaGame
        global oldMetaGame
        global scorePos
        global score
        global inGUI
        canvas.tick(self,delta)
        if(oldMetaGame!= metaGame):
            ScreenMessages.clearMessages()
            canvas.ressetTitle(self)
            inGUI = 1
            mouseEnabled = 1
            y = 50
            ScreenMessages.setMessageStatic(messages.puzzleTitle,None,-1,y,None )
            ScreenMessages.setMessageStatic(messages.returnMenu,None,-1,540,backtoMainScreenCurtains)   
                 
            oldMetaGame = metaGame
        else:
            self.life += 1
            
    def continueOption(self):
        fadeManager.fadeDown(menuItems.game)
      
    def noContinueOption(self):  
        profiles[currentProfile].puzzleCollumn = 0
        profiles[currentProfile].row = 0
        fadeManager.fadeDown(menuItems.game)

continuePuzzleCanvas = continuePuzzleScreen()
 

class continueActionScreen(canvas):
    exitFlag = 0    
    def render(self):
        character = self.animation[self.frameNumber][0]
        self.frame = None

        canvas.render(self)
        PC.setFont( font22 )  
        
    def tick(self,delta):    
        global metaGame
        global oldMetaGame
        global scorePos
        global score
        global inGUI
        canvas.tick(self,delta)
        if(oldMetaGame!= metaGame):
            ScreenMessages.clearMessages()
            canvas.ressetTitle(self)
            inGUI = 1
            mouseEnabled = 1
            y_delta = 40
            y = 200
            ScreenMessages.setMessageStatic(messages.ContinueAction,None,-1,y,None )
            y += 100
            ScreenMessages.setMessageStatic(messages.YesContinue,None,260,y, self.continueOption )

            ScreenMessages.setMessageStatic(messages.NoContinue,None,480,y, self.noContinueOption )
            y += y_delta

            x = 265
            y = 210
                 
            oldMetaGame = metaGame
            
    def continueOption(self):
        fadeManager.fadeDown(menuItems.game)
      
    def noContinueOption(self):  
        profiles[currentProfile].actionLevel = startLevel
        profiles[currentProfile].actionScore = 0
        profiles[currentProfile].actionLives= 0
        fadeManager.fadeDown(menuItems.game)

continueActionCanvas = continueActionScreen()

class continueCasualScreen(canvas):
#    character = "BiffTest"
    characterX = 550
    characterY = 350
    exitFlag = 0    
    def render(self):
        self.frame = None

        canvas.render(self)
        self.renderButtons()
        self.renderTitleBar()
        
    def renderTitleBar(self):
        PC.setColour(210, 190, 255, 180)
        level = profiles[currentProfile].casualLevel
        numberLevels = len(levelData.levels)
        clampedLevelNumber = level%numberLevels
        thisLevel = levelData.levels[clampedLevelNumber] 
        levelName = thisLevel.levelName
        string = "Continue at Level "+str(level+1)+" ?"
        font = font26
        width = PCR.stringWidth(string,font) + len(string) * 4
        x = 400 - (width/2.0)
        y = 270
        PC.setFont(font)     
        for char in string:
            PC.drawString(char,x,y) 
            x += PCR.stringWidth(char,font) + 4
        font = font16
        PC.setFont(font)
        string = levelName
        width = PCR.stringWidth(string,font) + len(string) * 4
        x = 400 - (width/2.0)
        y = 300
     
        for char in string:
            PC.drawString(char,x,y) 
            x += PCR.stringWidth(char,font) + 4

    def renderButtons(self):    
        if profiles[currentProfile].inputMode == 1:
            upColour = [210, 190, 255, 255]
            overColour = [255, 230, 255, 255]
            x = 300
            y = 200
            renderButtonWithText("yesContinue",400 - 222,380,"main_button_over",None,"YES",font26,upColour,overColour)
            renderButtonWithText("noContinue",401,380,"main_button_over",None,"NO",font26,upColour,overColour)   
        else:
            unselectedColour = [120, 80, 120, 255]
            selectedColour = [255, 230, 255, 255]
            if self.selectedOption == 1:
                renderButtonWithText("yesContinue",400 - 222,380,"main_button_over",None,"YES",font26,selectedColour,selectedColour)
                renderButtonWithText("noContinue",401,380,"main_button_over",None,"NO",font26,unselectedColour,unselectedColour) 
            else:
                renderButtonWithText("yesContinue",400 - 222,380,"main_button_over",None,"YES",font26,unselectedColour,unselectedColour)
                renderButtonWithText("noContinue",401,380,"main_button_over",None,"NO",font26,selectedColour,selectedColour) 

        
    def mouseClick(self,button):
        if button == 0:
            if clickOnButton("yesContinue"):
                self.continueOption()
            if clickOnButton("noContinue"):
                self.noContinueOption()      
        
    def tick(self,delta):    
        global metaGame
        global oldMetaGame
        global scorePos
        global score
        global inGUI
        canvas.tick(self,delta)
        if(oldMetaGame!= metaGame):
            ScreenMessages.clearMessages()
            canvas.ressetTitle(self)
            inGUI = 1
            mouseEnabled = 1
            y_delta = 40
            y = 200
           # ScreenMessages.setMessageStatic(messages.ContinueCasual,None,-1,y,None )

            x = 265
            y = 210
                 
            oldMetaGame = metaGame
            self.selectedOption = 1
        else:
            self.checkController()
            
    def checkController(self):
        canvas.controllerButtons(self)
        if self.startButton or  checkKeyNoRepeat(keyMap.spaceKey.keyValue) or  checkKeyNoRepeat(keyMap.enterKey.keyValue):
            if self.selectedOption==1:
                self.continueOption()
            else:
                self.noContinueOption() 
        elif self.leftButton or  checkKeyNoRepeat(keyMap.rightCursorKey.keyValue):
            self.selectedOption = 0
        elif self.rightButton or  checkKeyNoRepeat(keyMap.leftCursorKey.keyValue):
            self.selectedOption = 1    


    def continueOption(self):
        fadeManager.fadeDown(menuItems.game)
        game.level = profiles[currentProfile].casualLevel
        if profiles[currentProfile].casualLives <= 0:
            profiles[currentProfile].casualLives = 3
        #print "gamelevel",game.level
      
    def noContinueOption(self):  
        profiles[currentProfile].casualLevel = startLevel
        game.level = profiles[currentProfile].casualLevel
        profiles[currentProfile].casualScore = 0
        profiles[currentProfile].casualLives = 3        
        fadeManager.fadeDown(menuItems.game)

continueCasualCanvas = continueCasualScreen()

class instructionListCanvas(canvas):
    exitFlag = 0    
    InstructionIndex = 0
    def render(self):
        character = self.animation[self.frameNumber][0]
        self.frame = None

        canvas.render(self)
        PC.setFont( font22 )  
        
    def tick(self,delta):    
        global metaGame
        global oldMetaGame
        global scorePos
        global score
        global inGUI
        canvas.tick(self,delta)
        if(oldMetaGame!= metaGame):
            ScreenMessages.clearMessages()
            canvas.ressetTitle(self)
            inGUI = 1
            mouseEnabled = 1
            y_delta = 40
            y = 100
            ScreenMessages.setMessageStatic(messages.Instructions,None,-1,y,None )
            y += y_delta+20
            index = 0
            for instruction in messages.completeInstructions:  
                
                ScreenMessages.setMessageStatic(instruction[0],None,300,y,doInstruction,parameter=index,string ="...")
                y += y_delta
                index+= 1
            
            ScreenMessages.setMessageStatic(messages.backToOptions,None,-1,590,self.exit) 
            x = 265
            y = 210
                 
            oldMetaGame = metaGame
        
    def exit(self):
        fadeManager.fadeDown(menuItems.optionsCanvas)

instructionListCanvas = instructionListCanvas()

def doInstruction(index):
    instructionListCanvas.InstructionIndex = index
    fadeManager.fadeDown(menuItems.instructionCanvas)
    return

class instructionCanvas(canvas):
    exitFlag = 0    
    def render(self):
        character = self.animation[self.frameNumber][0]
        self.frame = None

        canvas.render(self)
        PC.setFont( font22 )  
        
    def tick(self,delta):    
        global metaGame
        global oldMetaGame
        global scorePos
        global score
        global inGUI
        canvas.tick(self,delta)
        if(oldMetaGame!= metaGame):
            ScreenMessages.clearMessages()
            canvas.ressetTitle(self)
            inGUI = 1
            mouseEnabled = 1
            y_delta = 50
            y = 150
            index = 0
            for instruction in messages.completeInstructions[ instructionListCanvas.InstructionIndex]:
                if index ==0:
                    ScreenMessages.setMessageStatic(messages.Blank36,None,-1,y,None,string = instruction[0])
                else:
                    ScreenMessages.setMessageStatic(instruction,None,-1,y,None)
                y += y_delta
                index += 1

            ScreenMessages.setMessageStatic(messages.MoreInstructions,None,-1,590,self.exit) 
            x = 265
            y = 210
                 
            oldMetaGame = metaGame
        
    def exit(self):
        fadeManager.fadeDown(menuItems.instructionListCanvas)

instructionCanvas = instructionCanvas()


class sellUpScreenExit(creditScreen):
    exitFlag = 1
    def exit(self):
        exitGameOption()

sellUpExitCanvas = sellUpScreenExit()

numberString = ["Off","Low","Med","High","Max"]

def getWordFromNumber(number):
    return numberString[number]
      

def changeSoundVolume():
    global oldMetaGame
    oldMetaGame = -1
    profiles[currentProfile].soundVolume += 1.0
    if(profiles[currentProfile].soundVolume>4):
        profiles[currentProfile].soundVolume = 0.0
    playSimpleSound( 'Ding')
    
def changeInputDevice():
    global oldMetaGame
    oldMetaGame = 0
    if(profiles[currentProfile].inputMode):
        profiles[currentProfile].inputMode = 0
    else:
        profiles[currentProfile].inputMode = 1
    
def changeMusicVolume():
    global oldMetaGame
    oldMetaGame = -1
    profiles[currentProfile].musicVolume += 1
    if(profiles[currentProfile].musicVolume>4):
        profiles[currentProfile].musicVolume =0
    setMusicVolume()

def setMusicVolume():
    internalVolume = -1.0
    musicVolume = profiles[currentProfile].musicVolume
    if musicVolume == 0:
        internalVolume = 0.0
    elif musicVolume == 1:
        internalVolume = 0.25 
    elif musicVolume == 2:
        internalVolume = 0.5       
    elif musicVolume == 3:
        internalVolume = 0.75     
    elif musicVolume == 4:
        internalVolume = 1.0   
    if internalVolume != -1.0:
        PC.setVolume( internalVolume )      
    
    
def ToggleWindowed():
    global oldMetaGame
    oldMetaGame = -1
    global fullScreenMode
    if(fullScreenMode):
        fullScreenMode = 0
        PC.setFullscreen(0)
    else:
        fullScreenMode = 1
        PC.setFullscreen(1)


def backtoMainScreen():
    global metaGame
    highScoreCanvas.cameFromLevel = 0
    fadeManager.fadeDown(menuItems.mainScreenCanvas)

def backtoMainScreenCurtains():
    global metaGame
    highScoreCanvas.cameFromLevel = 0
    fadeManager.fadeDown(menuItems.mainScreenCanvas,1)

optionsCanvas = optionsScreen()

def checkIfTutorialsEnabled():
    index = 62 # after the second half turn off tutorials
    if profiles[currentProfile].tutorials:
        return 1
    else:
        return 0
    
class particle:
    x=0
    y=0
    rotation = 0
    y_speed = 0 
    x_speed = 0
    angularVelocity =  0
    scale=1      #scale value for size
    r=255           #scale values for colour
    g=255
    b=255
    a=255
    width=1
    height=1
    frameNumber=-1      #start at minus one because first time through we'll increment this
    animation=None
    life=0
    name = ''
    frame = 0
    alphaDelta = 0
    scaleDelta = 0
    delete = 0
    frame = -1
    gravity = 0
    maximumYSpeed = 1000
    graphic=''
    overRideFrame = None # if this is set to true then we use this instead of the grahic in the particle data
    additive = 1
    
    def render(self):
        if(self.animation!=None):
            screenWidth = self.width*self.scale
            screenHeight = self.height*self.scale
            screenX = self.x-(screenWidth/2)
            screenY = self.y-(screenHeight/2)

            PC.setColour(self.r,self.g,self.b,self.a)
            if(self.frame >=0):
                frame = self.frame
                if self.additive:
                    PC.drawmodeAdd()
                if(self.animation[self.frameNumber][6]):
                    #rotating so can't scale
                    if(self.overRideFrame):
                        PC.drawmodeNormal() 
                        PC.drawImageRot(frame, screenX, screenY, self.rotation) 
                    else:
                        PC.drawImageRot(frame, screenX, screenY, self.rotation) 
                else:
                    if(self.overRideFrame):
                        PC.drawmodeNormal() 
                    else:
                        if self.additive:
                            PC.drawmodeAdd()
                    PC.drawImageScaled(frame, screenX, screenY,screenWidth,screenHeight)
                PC.drawmodeNormal()  
            
    def tick(self,delta):
        self.life-= delta
        self.y_speed += self.gravity
        if self.y_speed >self.maximumYSpeed:
            self.y_speed = self.maximumYSpeed
        self.y += self.y_speed*delta 
        self.x += self.x_speed*delta
        particle.stepAnimation(self,delta)
        #if(self.animation):
         #   self.angularVelocity = self.animation[self.frameNumber][6] 
        if(self.angularVelocity>0):
            self.rotation += self.angularVelocity*delta
        elif(self.angularVelocity<0):
            self.rotation += self.angularVelocity*delta   
            if(self.rotation<0):
                self.rotation += 2.0 * 22.0/7.0
        
    def stepAnimation(self,delta):
      
        if(self.life<=0):
            if(self.frameNumber==-1):
                self.frameNumber =0
            else:
                self.frameNumber = self.animation[self.frameNumber][1]
            self.graphic = self.animation[self.frameNumber][0]
            if(self.graphic=='end'):
            #We've reached the last frame
                self.animation = None
                self.delete = 1
            else:
                if self.overRideFrame:
                    self.frame = JPG_Resources[ self.overRideFrame]
                else:
                    self.frame = JPG_Resources[self.graphic]
                self.width= PCR.imageWidth( self.frame )
                self.height= PCR.imageHeight( self.frame )
                self.life = self.animation[self.frameNumber][2]  
                SFX = self.animation[self.frameNumber][3]
                if SFX != None:
                        playSimpleSound(SFX)  
                self.scaleDelta = self.animation[self.frameNumber][4]/1.333
                self.alphaDelta = self.animation[self.frameNumber][5]/1.333 

        else:
            self.life -= delta
            self.scale+=self.scaleDelta*delta
            self.a +=self.alphaDelta*delta
            if self.a > 255:
                self.a = 255
            if(self.a<0 or self.y > 800):
                self.a=0
                self.delete = 1 #delete particle if it's alpha is zero or it's off the screen


            
class tileExplosion(particle):
    name="tileExplosion"
    animation = particleEffects.tile_explosion
    additive = 0

            
class numberExplosion(particle):
    name="tileExplosion"
    animation = particleEffects.fairySparkle1
    additive = 0
    gravity = 0.05
    maximumYSpeed = 7.0

class spellParticle(particle):
    name="spellParticle"    
    animation = particleEffects.spell
    
class fairyTrailParticle(particle):
    name="fairyTrailParticle"    
    animation = particleEffects.fairyTrail
    
class fairySparleParticle1(particle):
    name="fairySparkleParticle1"    
    animation = particleEffects.fairySparkle1 
    gravity = 0.05
    maximumYSpeed = 7.0


class fairyTrailParticle2(particle):
    name="fairySparkleParticle"    
    animation = particleEffects.fairySparkle1 
    gravity = 0.1
    maximumYSpeed = 14.0
    additive = 0
    a=220
    
class acidParticle(particle):
    name="acid"    
    animation = particleEffects.acid 
    gravity = 0.1
    maximumYSpeed = 9.0
    additive = 0
    
class fairySparleParticle2(particle):
    name="fairySparkleParticle2"    
    animation = particleEffects.fairySparkle2 
    gravity = 0.07
    maximumYSpeed = 8.0  

class ghostParticle(particle):
    name="ghostParticle"    
    animation = particleEffects.ghostParticle
    gravity = 0.00
    maximumYSpeed = 7.0
    #additive = 0
 
class fairyAttackParticle1(particle):
    name="fairyAttack1"   
    animation = particleEffects.fairyAttack1 
    gravity = 0.2
    maximumYSpeed = 14.0
    
class fairyAttackParticle2(particle):
    name="fairyAttack2"    
    animation = particleEffects.fairyAttack2
    gravity = 0.12
    maximumYSpeed = 14.0   
     
class fireParticle1(particle):
    name="fire1"    
    animation = particleEffects.fire1 
    gravity = 0.05
    maximumYSpeed = 7.0

class fountainParticle(particle):
    name="fountain1"    
    animation = particleEffects.fountain1 
    gravity = 0.07
    maximumYSpeed = 7.0
    additive = 0

class fountainParticle2(particle):
    name="fountain2"    
    animation = particleEffects.fountain2 
    gravity = 0.08
    maximumYSpeed = 8.0
    additive = 0

class fountainParticle3(particle):
    name="fountain2"    
    animation = particleEffects.fountain2 
    gravity = 0.09
    maximumYSpeed = 9.0
    additive = 0

class fireParticle2(particle):
    name="fire2"    
    animation = particleEffects.fire2 
    gravity = 0.07
    maximumYSpeed = 8.0 
    additive = 0
    
class fireParticle3(particle):
    name="fire1"    
    animation = particleEffects.fire1 
    gravity = 0.05
    maximumYSpeed = 7.0      
    additive = 0    
class fireWorkParticle1(particle):
    name="fireWork1"    
    animation = particleEffects.fireWork1 
    gravity = 0.05
    maximumYSpeed = 8.0    
    additive = 0
class fireWorkParticle2(particle):
    name="fireWork1"    
    animation = particleEffects.fireWork2 
    gravity = 0.05
    maximumYSpeed = 8.0  
    
class fireWorkParticle3(particle):
    name="fireWork1"    
    animation = particleEffects.fireWork3 
    gravity = 0.05
    maximumYSpeed = 8.0     
    
class fairyRedTrailParticle(particle):
    name="fairyRedTrailParticle"    
    animation = particleEffects.fairyRedTrail  

class dustParticle(particle):
    name="DustParticle"    
    animation = particleEffects.dustPuff
    gravity = 0.05
    maximumYSpeed = 7.0
    
class hitEffectParticle(particle):
    name="hitEffectParticle"    
    animation = particleEffects.hitEffect
    gravity = 0.05
    maximumYSpeed = 7.0   
    
class spellExplosion(particle):
    name="spellExplosion"    
    animation = particleEffects.spell_explosion
    
class clockExplosion(particle):
    name="clockExplosion"
    animation = particleEffects.clock_explosion

class bigExplosion(particle):
    name="bigExplosion"
    animation = particleEffects.big_explosion

class vBigExplosion(particle):
    name="vBigExplosion"
    animation = particleEffects.big_explosion
    
particleGravity = .1

class gravityParticle(particle):
    def tick(self,delta):
        self.y_speed += particleGravity*delta
        particle.tick(self,delta)
    
class debris(gravityParticle):
    name = "debris"
    animation = particleEffects.debris
    def __init__(self,graphic=None,rotation=0):
        if(graphic):
            self.overRideFrame = graphic
        if(rotation):
            self.angularVelocity = rotation
            
class numberParticle(particle):
    name = "number"
    animation = particleEffects.number
    value = 0
    def __init__(self,number=0):
        self.value = number
        
    def render(self):
        particle.render(self)
        string = str(self.value)
        x = self.x
        y = self.y
        a = self.a
        b= 255
        r=g= 0
        drawStringDropShadow(string,x,y,r,g,b,a) 
            
class lockParticle(particle):
    name = "lock"
    animation = particleEffects.lock
    gravity = 0.2
    maximumYSpeed = 4
    additive = 0

class cageParticle(particle):
    name = "cage"
    animation = particleEffects.cage
    gravity = 0.2
    maximumYSpeed = 4
    additive = 0
            
class particleControllerClass:
    effectsList = []
   
    def addItem(self,effect,x,y,scale,xSpeed = 0,ySpeed = 0):
        effect.x = x
        effect.y = y
        effect.x_speed = xSpeed
        effect.y_speed = ySpeed
        effect.scale=scale
        self.effectsList.append(effect)
        
    def render(self):
        PC.setColourize(1)
        for item in self.effectsList:
            item.render()
            
    def tick(self,delta):
        for item in self.effectsList[:]:
            item.tick(delta)
            if(item.delete):
                self.effectsList.remove(item)
    def clearEffects(self):
        self.effectsList = []
                
particleController = particleControllerClass()


profileSaveFile = None

def openProfileDataForRead():
    global profileSaveFile
    try:
        path = localAppData+"/AtomicWorm/profiles.int"
        profileSaveFile = open( path, "r" )
    except IOError:
        print "file error not found"
        profileSaveFile = None
        

def openProfileDataForWrite():
    global profileSaveFile
    try:
        os.mkdir(localAppData+"/AtomicWorm")
    except:
        print "directory exists"
    path = localAppData+"/AtomicWorm/profiles.int"
    profileSaveFile = open( path, "w" )
 
def closeProfileData():
      global profileSaveFile
      profileSaveFile.close()
      profileSaveFile = 0

def writeReg(key,value):
    profileSaveFile.write(key+"\n")
    profileSaveFile.write(value+"\n")   
    
def readReg(key):   
    if key in Profile_Data:  
        value = Profile_Data[key]
    else:
        value = 0
    return value

def writeProfiles():
    openProfileDataForWrite()
    for profile in profiles:
        profile.writeRegistry()
    closeProfileData()
    
Profile_Data = {}    
    
def readProfiles():  
    global Profile_Data
    Profile_Data = {} 
    openProfileDataForRead()  
    key = 1
    if profileSaveFile != None:
        for line in profileSaveFile:
            if key:
                thisKey = line[:-1]
                key = 0
            else:
                value = line[:-1]
                Profile_Data[thisKey] = value
                key = 1
    for profile in profiles:
        profile.readRegistry()
    closeProfileData()

class profile:
    playerName = "Empty"
    index = 0
    inputMode = 1           #need to store to registry
    soundVolume = 2
    musicVolume = 2
    storyBegun = 0
    version = 1
    tutorials = 0
    puzzleCollumn = 0
    puzzleRow = 0
    actionLevel = startLevel
    actionScore = startLevel
    casuallevel = 0
    actionLevel = 0
    casualLives = 0
    actionLives = 0
    maxWidthPuzzle = 10
    maxHeightPuzzle = 10
    ticketsCollected = 0
    scoreMultiplierEnabled = 0
    
    def __init__(self,index):
        self.index = index
        self.ressetProfile()
            
    def getKey(self):
        return"profile"+str(self.index)+"/"

    def writeRegistry(self):
        writeReg(self.getKey()+"playerName",self.playerName)
        
        writeReg(self.getKey()+"Mouse",str(self.inputMode))
        writeReg(self.getKey()+"Sound",str(int(self.soundVolume)))
        writeReg(self.getKey()+"Music",str(int(self.musicVolume)))
        writeReg(self.getKey()+"StoryBegun",str(self.storyBegun))
        writeReg(self.getKey()+"Version",str(self.version))
        writeReg(self.getKey()+"tutorials",str(self.tutorials))
        writeReg(self.getKey()+"puzzleCollumn",str(self.puzzleCollumn)) 
        writeReg(self.getKey()+"puzzleRow",str(self.puzzleRow)) 
        writeReg(self.getKey()+"actionLevel",str(int(self.actionLevel)))    
        writeReg(self.getKey()+"casualLevel",str(int(self.casualLevel)))  
        writeReg(self.getKey()+"actionScore",str(int(self.actionScore)))    
        writeReg(self.getKey()+"casualScore",str(int(self.casualScore))) 
        writeReg(self.getKey()+"casualLives",str(int(self.casualLives))) 
        writeReg(self.getKey()+"actionLives",str(int(self.actionScore)))  
        writeReg(self.getKey()+"scoreMultiplierEnabled",str(int(self.scoreMultiplierEnabled))) 
#        self.writePuzzleBoard()
        
    def writePuzzleBoard(self):
        y = 0
        for row in self.puzzleLevelsSolved:
            x = 0
            for element in row:
                name = "puzzElement"+str(x)+str(y)
                elementValue = self.puzzleLevelsSolved[x][y]
                writeReg(self.getKey()+name,str(elementValue))  
                x += 1
            y += 1


    def readRegistry(self):  
        playerName = readReg(self.getKey()+"playerName")
        if playerName:
            self.playerName = playerName
            
            inputMode = readReg(self.getKey()+"Mouse")
            if inputMode:
                self.inputMode = int(inputMode) 
            
            soundVolume = readReg(self.getKey()+"Sound")
            if soundVolume:
                self.soundVolume = int(soundVolume)    

            musicVolume = readReg(self.getKey()+"Music")
            if musicVolume:
                self.musicVolume = int(musicVolume)

            tutorials = readReg(self.getKey()+"tutorials")
            if tutorials:
                self.tutorials= int(tutorials) 

            puzzleCollumn= readReg(self.getKey()+"puzzleCollumn")
            if puzzleCollumn:
                self.puzzleCollumn= int(puzzleCollumn)     

            puzzleRow = readReg(self.getKey()+"puzzleRow")
            if puzzleRow:
                self.puzzleRow= int(puzzleRow)       

            actionLevel = readReg(self.getKey()+"actionLevel")
            if actionLevel:
                self.actionLevel = int(actionLevel)   
                
            casualLevel = readReg(self.getKey()+"casualLevel")
            if casualLevel:
                self.casualLevel = int(casualLevel) 

            actionScore = readReg(self.getKey()+"actionScore")
            if actionScore:
                self.actionScore = int(actionScore)   
                
            casualScore = readReg(self.getKey()+"casualScore")
            if casualScore:
                self.casualScore = int(casualScore)               

            casualLives = readReg(self.getKey()+"casualLives")
            if casualLives:
                self.casualLives = int(casualLives)

            actionLives = readReg(self.getKey()+"actionLives")
            if actionLives:
                self.actionLives = int(actionLives)


            scoreMultiplierEnabled = readReg(self.getKey()+"scoreMultiplierEnabled")
            if scoreMultiplierEnabled:
                self.scoreMultiplierEnabled = int(scoreMultiplierEnabled)
              
            self.readPuzzleBoard() 

    def readPuzzleBoard(self):
        self.ressetPuzzlesSolved()
        y = 0
        for row in self.puzzleLevelsSolved:
            x = 0
            for element in row:
                name = "puzzElement"+str(x)+str(y)
                elementValue = readReg(self.getKey()+name) 
                if elementValue:
                    self.puzzleLevelsSolved[x][y] = int(elementValue)
                x += 1
            y += 1
            
    def getPuzzleElementValue(self,x,y):
        if x < 0 or x >= self.maxWidthPuzzle:
            return 0
        if y < 0 or y >= self.maxHeightPuzzle:
            return 0
        return self.puzzleLevelsSolved[x][y]
        
    def setPuzzleElementValue(self,x,y,value):
        self.puzzleLevelsSolved[x][y] = value   
      
                
    def ressetProfile(self):
        self.playerName = "Empty"

        
        self.inputMode = 1
        self.storyBegun = 0
        self.soundVolume = 2
        self.musicVolume = 2
        self.tutorials = 0
        self.puzzleCollumn = 0
        self.puzzleRow = 0
        index = 0
        self.actionLevel = startLevel
        self.casualLevel = startLevel
        self.actionScore = 0
        self.casualScore = 0
        self.scoreMultiplierEnabled =0 
        
    def ressetPuzzlesSolved(self):
        self.puzzleLevelsSolved = []
        for index in xrange(self.maxHeightPuzzle):
            row = []
            for index1 in xrange(self.maxWidthPuzzle):
                row.append(0)
            self.puzzleLevelsSolved.append(row)
        
      
profiles = [profile(0),profile(1),profile(2),profile(3),profile(4),profile(5)]


class InstructionManagerClass:
    anyKeyPressed = 1
    instructionsUp = 0
    backAlpha = 0
    targetBackAlpha = 0
    fairyFrameNumber = 0
    animationSwitch=10
    animation = animationSets.fairy_move
    frame = None
    fairyX = 0
    fairyY = 0
    fairyTargetX = 770
    fairyTargetY = 10
    fairyScale = 1
    rectX = 100
    rectY = 50
    rectWidth = 600
    rectHeight = 200
    fairAlpha = 0
    def showInstruction(self,instructions):
        global forcePause
        global instructionWait
        instructionWait = 1
        forcePause = 1
        self.fairyX = 830
        self.fairyY = -10
        self.fairyTargetX = 770
        self.fairyTargetY = 30
        self.targetBackAlpha = 255
        self.instructionsUp = 1
        self.anyKeyPressed = 1 #set this true initially 
        maxWidth = 0 
        self.rectHeight = 80
        ScreenMessages.lastMessageTabY  = 120

        for message in instructions:
            ScreenMessages.setMessageScroll(message,None)
            #print "Setting message",message
            ScreenMessages.lastMessageTabY -= 2
            if message[6] == 22:
                font = font23
            else:
                font = font38
            if font == None:
                return
            workingString = message[0]
            HighLight = workingString.find('__H')
            if HighLight != -1:
                HighLightDown = workingString.find('__N')
                right = workingString[:HighLight]
                left = workingString[HighLightDown+3:]
                highLightString = workingString[HighLight+3:HighLightDown]
                workingString = right + highLightString +  left
            width = PCR.stringWidth(workingString,font)
            self.rectHeight += 40
            if width > maxWidth:
                maxWidth = width
        self.rectY = ScreenMessages.lastMessageTabY - self.rectHeight+ 80
        self.rectWidth = maxWidth
        self.fairyX = 335 + maxWidth/2
        self.fairyY = 25
        self.rectX = (800 - self.rectWidth)/2
#        ScreenMessages.setMessageScroll(messages.Blank22,None)  
        ScreenMessages.setMessageScroll(messages.ClickHere,None,function = self.continueGame)  
    
    def continueGame(self):
        global forcePause
        forcePause = 0
        self.targetBackAlpha = 0
        self.instructionsUp = 0
        self.fairyAlpha = 0
        if ScreenMessages and metaGame==0:
            ScreenMessages.fadeAndClear()   
        setTargetVolume(1)
        
    def tick(self,delta):        
        if self.fairyScale  < 1.5:
            self.fairyScale += delta/200.0             
        self.animationSwitch -= delta;
        if(self.animationSwitch<= 0):
            self.fairyFrameNumber = self.animation[self.fairyFrameNumber][1]
            self.animationSwitch = self.animation[self.fairyFrameNumber][2]        
        if noKeyDown():
            self.anyKeyPressed = 0
        if metaGame:
            self.targetBackAlpha = 0
            
        if self.targetBackAlpha:    
            setTargetVolume(quietMusic)

        if anyKeyDown() and self.anyKeyPressed==0 and forcePause==1:
            self.continueGame()
        if(self.backAlpha<self.targetBackAlpha):
            self.backAlpha += delta*4
            if(self.backAlpha>self.targetBackAlpha):
                self.backAlpha = self.targetBackAlpha
        if(self.backAlpha>self.targetBackAlpha):
            self.backAlpha -= delta*4
            if(self.backAlpha<self.targetBackAlpha):
                self.backAlpha = self.targetBackAlpha
    def render(self):
        if  self.backAlpha: 
            PC.setColourize(1)          
            PC.setColour( 255, 255, 255, self.backAlpha)
            res = JPG_Resources['helpBack'] 
            PC.drawmodeNormal()
            PC.drawImageScaled( res, self.rectX,self.rectY,self.rectWidth,self.rectHeight)
#            self.renderFairy(self.fairyX,self.fairyY,self.fairyScale)
            
    def renderFairy(self,x,y,scale):
        name = self.animation[self.fairyFrameNumber][0]
        self.frame = JPG_Resources[name]
        if(self.frame != None):
            PC.setColourize(1)          
            PC.setColour( 255, 255, 255, self.backAlpha)
            width = PCR.imageWidth(self.frame)
            height = PCR.imageHeight(self.frame)
            PC.drawImageScaled( self.frame, x, y,width*scale,height*scale)
    


instructionManager = InstructionManagerClass()

class cutSceneClass(canvas):
    nextEvent = 0
    running = 0
    backDrop = None
    stepTimer = 0
    openingScene = 0
    anyKeyPressed = 1
    cutSceneNumber = 1
    cutScenePtr = None
    cutSceneTitle = None
    commands = None
    nextCommand = 0
    tabY = 0
    ForeGroundAlpha = 255
    fadeSpeed = 0
    higherScenery = []
    lowerScenery = []
    
    def startNew(self):
        global objects
        global cameraX
        global cameraY

        self.stepTimer=0
        self.nextEvent = 0
        self.nextCommand = 0
        self.ForeGroundAlpha = 255
        self.tabY = 60
        ScreenMessages.clearMessages()
        self.running = 1
        self.stepTimer = 10
        self.cutScenePtr = cutScenes.cutsceneList[self.cutSceneNumber]
        self.backDrop = self.cutScenePtr[0]
        self.stepTimer = self.cutScenePtr[1]
        self.commands = self.cutScenePtr[2]
        self.music = self.cutScenePtr[3]
        self.lowerScenery = self.cutScenePtr[4]
        self.higherScenery = self.cutScenePtr[5]
        if self.music != "":
            (self.music,1)
            playTuneOgg (self.music,1)
        else:
            stopTuneOgg()
        #ScreenMessages.setMessageStatic(messages.Blank36,None,-1,self.tabY,None,self.cutSceneTitle)
        objects = []
        cameraX = 0
        cameraY = 0
        fairyPointer.stop()
        particleController.clearEffects()

    def setAnimation(self,ID,animation):
        for object in objects:
            if object.ID == ID:
                object.animation = animation
                object.frameNumber = 0
      
    def addStartButton(self):
        self.tabY += 20
        ScreenMessages.setMessageStatic(messages.Continue,None,-1,self.tabY,self.exit)
        
    def addEndButton(self):
        self.tabY += 20
        ScreenMessages.setMessageStatic(messages.TheEnd,None,-1,self.tabY,self.exit)
    def render(self):
      
        self.renderBackDrop()
        self.renderScenery()
        self.renderObjects()

        
    def createObject(self,type,x,y,ID):
        global objects
      #  import copy
        newObject = copy.copy(AllWorldObjects[int(type)])
        newObject.setUpGraphics()
        newObject.x = x
        newObject.y = y
        newObject.targetX = x
        newObject.targetY = y
        newObject.ID= ID
        objects.append(newObject)
        
    def moveObject(self,ID,x,y):
        for object in objects:
            if object.ID == ID:
                object.x = x
                object.y = y
                
    def setTarget(self,ID,x,y):
        for object in objects:
            if object.ID == ID:
                object.targetX = x
                object.targetY = y
                
    def tickObjects(self,delta):
        for object in objects:
            object.tick(delta)
            
    def renderObjects(self):
        for object in objects:
            object.render()
            
    def startFadeOutForeground(self,fadeSpeed):
        self.fadeSpeed = fadeSpeed
        
    def fadeForGround(self,delta):
        self.ForeGroundAlpha += self.fadeSpeed*delta
        if self.ForeGroundAlpha<0:
            self.ForeGroundAlpha = 0
            self.fadeSpeed = 0
        if self.ForeGroundAlpha>255:
            self.ForeGroundAlpha = 255
            self.fadeSpeed = 0              
      
    def tick(self,delta):
        global oldMetaGame
        global cameraX
        global cameraY
        canvas.tick(self,delta)
        cameraX = 0
        cameraY = 0
        if(oldMetaGame!= metaGame):
            self.startNew()
            oldMetaGame = metaGame
        else:
            self.tickObjects(delta)
            if self.nextCommand < len(self.commands):
                self.stepTimer -= delta
                if self.stepTimer <=0:
                    commandPtr = self.commands[self.nextCommand]
                    self.stepTimer = commandPtr[0] #set up the timer
                    if commandPtr[1] == cutScenes.StringCommmand:
                        self.printString(commandPtr)
                    if commandPtr[1] == cutScenes.VerticalTab:
                        self.tabY +=  int(commandPtr[2])   
                    if commandPtr[1] == cutScenes.SpawnObject:
                        self.createObject(commandPtr[2],commandPtr[3],commandPtr[4],commandPtr[5])
                    if commandPtr[1] == cutScenes.MoveObject:
                        self.moveObject(commandPtr[2],commandPtr[3],commandPtr[4])
                    if commandPtr[1] == cutScenes.setTarget:
                        self.setTarget(commandPtr[2],commandPtr[3],commandPtr[4])   
                    if commandPtr[1] == cutScenes.fadeOutForeground:
                        self.startFadeOutForeground(commandPtr[2])
                    if commandPtr[1] == cutScenes.setAnimation:
                        self.setAnimation(commandPtr[2],commandPtr[3])  
                    if commandPtr[1] == cutScenes.addStartButton:
                        self.addStartButton()
                    if commandPtr[1] == cutScenes.addEndButton:
                        self.addEndButton()
                    self.nextCommand+=1
                if noKeyDown():
                    self.anyKeyPressed = 0
                if (anyKeyDown() and self.anyKeyPressed==0) :
                    self.exit()
            else:
                fairyPointer.enabled  = 1
            self.fadeForGround(delta)
                
    def printString(self,commandPtr):
        string = commandPtr[2]
        sound = commandPtr[3]
        fadeUpTime = 100.0
        if commandPtr[8] == 22:
            message = messages.Blank22Light
        else:
            message = messages.Blank36Light
        ScreenMessages.setMessageStatic(message,None,-1,self.tabY,None,string,fadeUp = fadeUpTime)
        self.tabY += 30
        
    def renderBackDrop(self):
        PC.drawmodeNormal()
        if self.backDrop:
            backDropManager.checkAndReload(self.backDrop)
            backDropRes = backDropManager.backDropResource
            PC.drawImage( backDropRes, 0,0)

    def renderScenery(self):
        x = 100
        for item in self.lowerScenery:
            res = JPG_Resources[item]
            width = PCR.imageWidth(res)
            height = PCR.imageHeight(res)
            y = 600 - height
            PC.drawImage( res, x, y)  
            x += width + 50
        x = 100
         
        for item in self.higherScenery:
            res = JPG_Resources[item]
            width = PCR.imageWidth(res)
            height = PCR.imageHeight(res)
            y = 0
            PC.drawImage( res, x, y)  
            x += 300           
        PC.setColour(0,0,0,self.ForeGroundAlpha)
        PC.fillRect( 0,0,800,600)

            
    def exit(self):
        global metaGame
        self.running = 0
        metaGame = 3
        fairyPointer.enabled  = 1 #has to be done here too in case of escape key
        
cutScene = cutSceneClass()

class FadeManagerClass:
    alpha = 0
    curtains = 0
    speed = 0
    direction = 0
    nextMetaGameMenu = 0
    def tick(self,delta):   
        global metaGame
        global startGame
        if self.direction <0:
            if self.alpha > 0:
                self.alpha -= self.speed*delta
            if self.alpha <= 0:
                self.alpha =0
                self.direction = 0
        if self.direction >0:
            if self.alpha < 256:
                self.alpha += self.speed*delta
            if self.alpha >= 255:
                self.alpha = 255
                self.direction = 0
                
                if self.nextMetaGameMenu != -1:
                    if self.nextMetaGameMenu == menuItems.replayLevel:
                        replayLevel()
                    elif self.nextMetaGameMenu == menuItems.arcadeLevel:
                        #print "starting arcade",levelNumber
                        startArcadeGame(levelNumber/levelsPerArcadeSegment)
                    else:
                        metaGame = self.nextMetaGameMenu
                        startGame = 1
              
    def render(self):
        if self.alpha >0:
            PC.setColourize(1)
            PC.setColour(0,0,0,self.alpha)
            PC.fillRect( 0,0,800,600)
            PC.setColourize(0)
            
    def fadeDown(self,nextMetaGame,curtains = 0):
        self.nextMetaGameMenu = nextMetaGame
        self.direction = 1
        self.curtains = curtains

        self.speed = 6
            
    def fadeUp(self):
        self.direction = -1
        self.speed = 6
      
    def fadeUpIfReady(self):
        if self.direction == 0:
            self.direction = -1
        
    def finished(self):
        return self.direction == 0

fadeManager = FadeManagerClass()

class notUsed:
    def tick():
        return 0
    def render():
        return 0

class sellUpScreen(canvas):
    exitFlag = 0    
    def render(self):
        character = self.animation[self.frameNumber][0]
        self.frame = None
        #self.title = JPG_Resources[ 'Options']

        canvas.render(self)
 
        x = 0
        y = 300
                
    def backToStory(self):
        fadeManager.fadeDown(menuItems.storyCanvas)
        
    def tick(self,delta):    
        global metaGame
        global oldMetaGame
        global scorePos
        global score
        global inGUI
        canvas.tick(self,delta)
        if(oldMetaGame!= metaGame):
#            playTuneOgg("Level3.ogg",1)
            ScreenMessages.clearMessages()
            canvas.ressetTitle(self)
            inGUI = 1
            mouseEnabled = 1
            y_delta = 40
            y = 50
            ScreenMessages.setMessageStatic(messages.buyUp6,None,-1,y,None )
            y += 200
            ScreenMessages.setMessageStatic(messages.buyUp7,None,-1,y,None )
            y += y_delta
            ScreenMessages.setMessageStatic(messages.buyUp8,None,-1,y,None )
            y += y_delta + 40
            ScreenMessages.setMessageStatic(messages.buyUp9,None,-1,y,None )
            y += y_delta
            ScreenMessages.setMessageStatic(messages.buyUp10,None,-1,y,None )
            y += y_delta +20 
            ScreenMessages.setMessageStatic(messages.TweelerWeb,None,-1,y,tweelerWebsite)  
            y += y_delta + 20           
            ScreenMessages.setMessageStatic(messages.CharlieWeb,None,-1,y,charlieWebsite)  
            y += y_delta + 20           
            ScreenMessages.setMessageStatic(messages.Quit,None,-1,y,self.exit1) 

                 
            oldMetaGame = metaGame
            
    def buyGame(self):
        if superior:
            openWebPage("https://secure.bmtmicro.com/servlets/Orders.ShoppingCart?PRODUCTID=28610000&CID=4&AID=709763")  
        else:
            openWebPage("https://secure.bmtmicro.com/servlets/Orders.ShoppingCart?CID=2861&PRODUCTID=28610000")
        global doExit
        doExit = 1        

    def snakeWebsite(self):
        openWebPage("http://www.charliedoggames.com/?page_id=3")
        
    def exit1(self):
        global doExit
        doExit = 1

def charlieWebsite():
        openWebPage("http://www.charliedoggames.com")        

def tweelerWebsite():
        openWebPage("http://www.tweeler.com")

sellUpCanvas = sellUpScreen()


class sellUpScreenExit(sellUpScreen):
    exitFlag = 1
    def exit(self):
        exitGameOption()

sellUpExitCanvas = sellUpScreenExit()        
class menuItems: 
    game,highScoreCanvas,optionsCanvas,nameCanvas,profileCanvas,cutScene,mainScreenCanvas,replayLevel,welcomeCanvas,cheatCanvas,creditCanvas,sellUpExitCanvas,arcadeLevel,instructionListCanvas,instructionCanvas,continuePuzzleCanvas,continueActionCanvas,continueCasualCanvas = range(18)
    
menuClasses = [notUsed,highScoreCanvas,optionsCanvas,nameCanvas,profileCanvas,cutScene,mainScreenCanvas,notUsed,welcomeCanvas,cheatCanvas,creditCanvas,sellUpExitCanvas,notUsed,instructionListCanvas,instructionCanvas,continuePuzzleCanvas,continueActionCanvas,continueCasualCanvas]    

def numberToString(number):
#takes a number and returns it as an integer string with commas seperating the thousands
    output = ""
    newNumber = int(number)
    while newNumber>999:
        numberString = str(newNumber)[-3:]
        output = ","+numberString+output
        newNumber /= 1000
    output = str(newNumber)+output 
    return output
    
def setLocalAppData():
    global localAppData
    string = "not set"
    localAppData = PC.getAppDataFolder()
    try:
        os.mkdir(localAppData+"/AtomicWorm")
        path = localAppData+"AtomicWorm/profiles.int"
        profileSaveFile = open( path, "w" )
        profileSaveFile.close()
    except:
        print "directory exists",localAppData+"/AtomicWorm"
    print "user path",localAppData
    
def StartGameDraw():
    if metaGame >=1:
        menuClasses[metaGame].render()
 
level1ElementGraphics = ["Flower03","Flower06","Flower07","Flower08","Amethyst","Ruby","Sapphire","Ball","Black","Bomb"]

level1ElementGraphics = ["Flower06","Ruby","Ball","Flower08","Amethyst","Flower07","Sapphire","Flower03","Black","Bomb"]

class elements:
    element0,element1,element2,element3,element4,element5,element6,element7,element8,bomb,oneUp = range(11)

class gameParticle:
    def __init__(self,res,x,y,scale,rotation,scaleDelta,rotationDelta,lifeDelta,additive):
      self.res = res
      self.width = PCR.imageWidth(self.res)
      self.height = PCR.imageHeight(self.res)
      self.x = x
      self.y = y
      self.scale = scale
      self.rotation = rotation
      self.scaleDelta = scaleDelta
      self.rotationDelta = rotationDelta
      self.lifeDelta = lifeDelta
      self.maxLife = 255
      self.life = self.maxLife
      self.remove = 0
      self.additive = additive
      
    def tick(self,delta):
      self.life -= delta * self.lifeDelta 
      if self.life <= 0:
          self.life = 0
          self.remove = 1
      self.rotation += self.rotationDelta
      self.scale += self.scaleDelta
          
    def render(self):
        res = self.res
        x = self.x - (self.width * 0.5)
        y = self.y - (self.height * 0.5)
        scale = self.scale
        rotation = self.rotation
        PC.setColourize(1)
        if self.additive:
            PC.drawmodeAdd()
        else:
            PC.drawmodeNormal()
        alpha = clamp255(self.life)*0.4
        PC.setColour( 255, 255, 255, alpha)                     
        PC.drawImageRotScaled(res,x,y,rotation,scale,scale) 
        
        
class gameClass:
    time = 0
    gamePaused = 0
    gameOver =0
    boardInstructions =0
    replayOptionY = 300 
    quitOptionY = 400
    continueOptionY = 500
    gamePaused = 0
    pausedAlpha = 0
    pauseButtonY = 550
    pauseButtonX = 660
    ressetButtonX = 10
    grid =None
    gridPixelSize = 400
    gridXOffset = 200
    gridYOffset= 100
    elementGraphics = []
    gridWidth = 7
    gridHeight = 7
    respawnTime = 24000
    comboLevel = 0
    moverSpeed = 0
    maxMoverSpeed = 0
    inputMode = 0
    messageString = ""
    messageAlpha = 0
    messageTime = 0
    exitActive = 0
    levelComplete =0
    outOfLevel = 0
    gameClock = 0
    gridAnimationTimer = 0
    numberTokens = 0
    fraction = 0
    visibleFraction = 0
    rotationSpeed = 0
    bombCount = 0
    oneUpCount = 0
    bombRespawnCount = 50
    pathHint = None
    currentPathHint = None
    pallet = pallet1
    pallets = [pallet1,pallet2,pallet3,pallet4,pallet5,pallet6]  
    waveSpeed = 0
    dynamicScale = 0
    player = None
    #inputMode = 0
    enemyFearcount = 0
    enemyFearcountMaximum  = 1000
    nextEnemySpawnCounter = 0
    numberEnemies = 0 
    requiredNumberEnemies = 0
    playerLives = 0
    startButtonClear =0
    backButtonClear = 0
    lives = 0
    gameParticles = []
    maxMessageTime = 200
#    poem = None
    tutorial = None
    showDirectionIndicator = 0

    
    def tickGameParticles(self,delta):
        for gameParticle in self.gameParticles[:]:
            gameParticle.tick(delta)
            if gameParticle.remove:
                self.gameParticles.remove(gameParticle)
                
    def renderGameParticles(self):
        for gameParticle in self.gameParticles:
            gameParticle.render()      

    def addParticle(self,res,x,y,scale,rotation,scaleDelta,rotationDelta,lifeDelta,additive):
        particle = gameParticle(res,x,y,scale,rotation,scaleDelta,rotationDelta,lifeDelta,additive)
        self.gameParticles.append(particle)
                
    def mouseWheel(self,mouseDelta):
        return 0
    
    def getNextTypeIndex(self):
        nextIndex = -1
        if self.bombCount:
            self.bombCount -= 1
            if self.bombCount == 0:
                self.bombCount = self.getTimeToNextBomb()
                nextIndex = elements.bomb
        if nextIndex == -1: 
            if self.oneUpCount:
                self.oneUpCount -= 1
                if self.oneUpCount <= 0:
                    nextIndex = elements.oneUp          
        if  nextIndex == -1:   
            nextIndex = random.randint(0,self.numberTokens)
        return nextIndex
    
    def mouseDown(self,button):
        if self.tutorial:
            self.tutorialFadeOut = 1
        elif self.gamePaused:
            self.gamePausedOptions(button)
        elif self.gameOver:
            self.gameOverOptions()
        elif self.outOfLevel:
            self.levelCompleteOptions()
        elif self.player:
            self.player.mouseDown(button)
        return 0
        
    def controllerButtons(self):
        buttons = getController(6)
        leftShoulder = buttons & 256
        rightShoulder = buttons & 512
        AButton = buttons & 4096
        BButton = buttons & 8192
        leftButton = buttons & 4
        rightButton = buttons & 8
        backButton = buttons & 32
        startButton = buttons & 16
        if startButton == 0:
            self.startButtonClear = 1
        if backButton == 0:
            self.backButtonClear = 1
            
        if self.gamePaused == 0 and backButton:
            self.gamePaused = 1
            self.backButtonClear = 0
        elif self.gamePaused and ( (backButton and self.backButtonClear) or checkKeyNoRepeat(keyMap.spaceKey.keyValue)):
            self.returnToMain()
        elif self.gamePaused and (startButton or checkKey(keyMap.spaceKey.keyValue)):
            self.startButtonClear = 0
            self.gamePaused = 0
        elif self.gameOver and (backButton or checkKey(keyMap.spaceKey.keyValue)):
            self.gameOverOptions()
        elif self.outOfLevel and (startButton or checkKey(keyMap.spaceKey.keyValue)):
            self.levelCompleteOptions()
        elif AButton:
            self.player.AButton()   
        if self.tutorial and  (startButton or checkKeyNoRepeat(keyMap.spaceKey.keyValue)):
            self.tutorialFadeOut = 1
                  

    def setUpGameClass(self):
        self.grid = gridClass()
        return 0
        
    def newGame(self):
        self.lives = profiles[currentProfile].casualLives
        return 0
    
    def tutorialFadeDown(self,delta):
        self.tutorialAlpha -= delta*4
        if self.tutorialAlpha<= 0:
            self.tutorialAlpha = 0
            self.tutorial = None   
    def tick(self,delta):
        if metaGame != oldMetaGame:
            self.setUp(delta)
        else:
            if self.tutorial:
                self.controllerButtons()
                if self.tutorialFadeOut:
                    self.tutorialFadeDown(delta)
                
            else:
                self.gameClock += delta
                self.scanKeyboard()
                self.controllerButtons()
                self.grid.tick(delta)
                self.tickMovers(delta)
                self.tickDisplayScore(delta)
                self.tickRespawnTime(delta)
                self.tickMoverSpeed(delta)
                self.tickMessage(delta)
                self.tickGameParticles(delta)
                if currentPoem:
                    currentPoem.tick(delta,1)
                if self.outOfLevel:
                    self.tickLevelComplete(delta)
                self.checkEnemySpawn(delta)   
                if self.gameOver:
                    self.gameOverTick(delta)
                    
                    
    def gameOverTick(self,delta):            
        self.gameOverTimer -= delta
        if self.gameOverTimer < 0:
            self.gameOverTimer = 0
                
    def tickLevelComplete(self,delta):
#        if currentPoem:
#            currentPoem.tick(delta)
        return 0    
            
    def tickRespawnTime(self,delta):
          current = self.respawnTime
          current *= 0.00001 
          self.respawnTime -= (current * delta)
          #print "respawnTime",self.respawnTime

            
    def getPlayerSpeed(self):
        speed = self.moverSpeed
        if self.bonusMultiplier:
            speed += 0.1
        return speed
            
    def tickMoverSpeed(self,delta):
          
 #         if game.exitActive:
 #             speedDelta = (self.maxMoverSpeed*2) - self.moverSpeed
 #             self.moverSpeed += delta * speedDelta * .00003
 #         else:
        speedDelta = self.maxMoverSpeed - self.moverSpeed
        self.moverSpeed += delta * speedDelta * .000025

    def render(self):

        #main render point for game
        if currentPoem and self.outOfLevel==0:
            currentPoem.render(1)
        self.renderBackGround()

        self.renderDebug()

        self.grid.render()
        self.renderMovers()
        self.renderGameParticles()
        
        if  self.levelComplete == 0:
            if self.pathHint:
                self.pathHint.renderHint1()
            if self.currentPathHint:
                self.currentPathHint.renderHint2()

        if self.gameOver==1:
            self.gameOverRender()
        elif self.outOfLevel:    
            self.levelCompleteRender()
        elif self.gamePaused:
            self.gamePausedRender()

        self.renderInstructions()
        if self.outOfLevel == 0:
            self.renderHUD()
            #self.renderLevelDebugInfo()
        if self.tutorial:
            self.tutorial.render()
        return 0
        
    def renderHUD(self):   
        y = 50
        PC.drawmodeAdd() 
        #setPalletColour(self.pallet.colour1,255) 
        self.pallet.setColourByIndex(0,255)        
        self.renderScore()
        #self.renderLevel()
        self.renderLives()
        self.renderMultiplier()
        PC.drawmodeNormal()
        self.renderCollected()          
        self.renderMessage()    
        
    def gameOverRender(self): 
        self.pallet.setColourByIndex(1,255) 
        limit = int(self.gameOverTimer)
        yOffset = random.randint(0,limit) -(limit *0.5)
        xOffset = random.randint(0,limit) -(limit * 0.5)
        drawStringCentred("Game Over",400+xOffset,200+yOffset,font44)    
        self.pallet.setColourByIndex(2,255)  
        drawStringCentred("Click to Return to Main Menu",400,260,font30)  

    def levelCompleteRender(self):
        #if currentPoem:
        #    currentPoem.render()
        #alpha = 135 + (math.sin(self.gameClock*0.1)*120)
        setPalletColour(self.pallet.colour4,self.messageAlpha*0.4)   
        
        y = 250
        drawStringCentred("Completed :  "+self.levelName,400,y,font26)  
        y += 55
        drawStringCentred("Element :  "+str(self.level+1) +"  of  " + str(self.numberLevels),400,y,font26)        
        y += 55
        drawStringCentred("Combos Collected :  "+str(int(self.levelComboCount)),400,y,font26)        
        y += 55
        drawStringCentred("Level Score :  "+str(int(self.levelScore)),400,y,font26) 
        y += 55
        drawStringCentred("Total Score :  "+str(int(self.score)),400,y,font26)        
        y += 60    
        drawStringCentred("Click for Next Level",400,y,font26)       
        y += 55  
        if (self.level+1)%5 == 0:
            alpha = self.messageAlpha*0.8
            colourIndex = random.randint(0,4)
            xOffset = random.randint(0,4)
            yOffset = random.randint(0,4)
            game.pallet.setColourByIndex(colourIndex,alpha)  
            y = 50
            drawStringCentred("Continue point reached!",400+xOffset,y+yOffset,font26)    
            
    def gamePausedRender(self):
        PC.setColour(0,0,0,170)
        PC.fillRect(0,0,800,600)
        upColour = game.pallet.returnColourByIndex(1,255)
        overColour = game.pallet.returnColourByIndex(0,255)
        
        renderButtonWithText("yesContinue",290,180,"main_button_over",None,"Continue",font30,upColour,overColour)
        renderButtonWithText("noContinue",290,100,"main_button_over",None,"Main Menu",font30,upColour,overColour)  



    def renderInstructions(self):
        if self.showBoardInstructions:
            if self.instructionAlpha < 255:
                self.instructionAlpha += 12
                if self.instructionAlpha > 255:
                    self.instructionAlpha = 255
        else:
            if self.instructionAlpha > 0:
                self.instructionAlpha -= 12
                if self.instructionAlpha < 0:
                    self.instructionAlpha = 0 
        if self.instructionAlpha and self.boardInstructions:
            res = JPG_Resources[self.boardInstructions] 
            PC.setColourize(1)
            PC.setColour(255,255,255,self.instructionAlpha)  
            x = 0
            y = 0
            PC.drawImage(res,x,y)          
            PC.setColourize(0)
            PC.setFont(font23)
            PC.setColour( 255,255,255,self.instructionAlpha )
            string = "Click to Continue"
            x =270
            y = 590
            PC.drawString( string,x, y )   
            
    def gameOverOptions(self):
        self.tempScore = self.score
        profiles[currentProfile].casualLives = self.lives
        profiles[currentProfile].casualScore = 0
        continueLevel = (int((profiles[currentProfile].casualLevel)/5))*5
        profiles[currentProfile].casualLevel = continueLevel
        self.score = 0
        self.returnToMain()
            
    def levelCompleteOptions(self):
        profiles[currentProfile].casualLives = self.lives
        profiles[currentProfile].casualScore = self.score
        self.nextLevel()

    def gamePausedOptions(self,button):
            if clickOnButton("noContinue"):
                self.score = 0
                self.returnToMain()
            if clickOnButton("yesContinue"):
                self.gamePaused = 0
                self.messageTime = self.maxMessageTime
            
    def renderPauseFade(self):
        if self.gamePaused:
            if self.pausedAlpha < 180:
                self.pausedAlpha += 12
                if self.pausedAlpha > 180:
                    self.pausedAlpha = 180

            
        else:
            if self.pausedAlpha > 0:
                self.pausedAlpha -= 12
                if self.pausedAlpha < 0:
                    self.pausedAlpha = 0   
        if self.pausedAlpha:                  
            PC.setColour(0, 0, 0,self.pausedAlpha)
            PC.fillRect(0,0,800,600)       
        
        
    def renderBackGround(self):
        if self.outOfLevel:
            name = "menu_background"
        else:
            name = "main_background"
        res = JPG_Resources[name]
        #PC.drawImage(res,0,0)
        #PC.setColour(0,0,0,32)
        PC.setColourize(1)
        #setPalletColour(game.pallet.colour5,32)
        r = game.pallet.colour2[0]
        g = game.pallet.colour2[1]
        b = game.pallet.colour2[2]
        PC.setColour(r,g,b,32)
        PC.drawImage(res,0,0)
        #PC.fillRect(0,0,800,600)


        
    def renderPauseButton(self):
        if game.gamePaused==0:
            font = font22
            PC.setFont(font)
            x = self.pauseButtonX 
            y = self.pauseButtonY
            res = JPG_Resources["Button"]
            if mousey < y+43 and mousey > y and mousex > x:
                PC.setColour(255,255,255,255)
            else:
                PC.setColour(200,200,200,255)
            PC.setColourize(1)
            PC.drawImage(res,x,y)
            PC.setColourize(0)
            string = "PAUSE"
            PC.setColour(0,0,0,255)
            PC.drawString(string,x+25,y+32)
        
    def renderRessetButton(self):
        if game.gamePaused==0:
            font = font22
            PC.setFont(font)
            x = self.ressetButtonX 
            y = self.pauseButtonY
            res = JPG_Resources["Button"]
            if mousey < y+43 and mousey > y and mousex < x+ 140:
                PC.setColour(255,255,255,255)
            else:
                PC.setColour(200,200,200,255)
            PC.setColourize(1)
            PC.drawImage(res,x,y)
            PC.setColourize(0)
            string = "RESET"
            PC.setColour(0,0,0,255)
            PC.drawString(string,x+15,y+32)        

    def instructionOptions(self):
        self.showBoardInstructions = None
        
    def drawStringHud(self,string, x, y): 
        PC.setColour( 55, 170, 63, 255) 
        PC.drawString(string, x-2, y-2)
        PC.drawString(string, x+2, y-2)
        PC.drawString(string, x-2, y+2)
        PC.drawString(string, x+2, y+2)
        PC.drawString(string, x-2, y)
        PC.drawString(string, x+2, y)        
        PC.setColour( 200, 250, 12,255)         
        PC.drawString(string, x, y)
                

    def renderDebug(self): 

        return 0
        
    def renderEditorHUD(self):
        PC.setFont(font23)
        x = 330
        y = 40
        string = "Editor Mode"
        PC.setColour( 255,0,0, 255) 
        PC.drawString(string, x, y)   
          
    def scanKeyboard(self):   
      
#        if checkKey(keyMap.sorKey.keyValue):
#            game.inputMode = 1
#        if checkKey(keyMap.rightCursorKey.keyValue): 
#            game.inputMode = 1 
            
        if checkKey(keyMap.cheatKey.keyValue) and cheatsActive: 
            self.doCheat()
            
        if cheatCanvas.active:
            if checkKeyNoRepeat(keyMap.editorKey.keyValue): 
                if self.inEditor:
                    self.inEditor = 0
                else:
                    self.inEditor = 1
            if checkKeyNoRepeat(keyMap.cheatKey.keyValue) and cheatsActive: 
                self.skipLevel()
        if checkKeyNoRepeat(keyMap.escapeKey.keyValue): 
            #need to add pause option here
            if self.showBoardInstructions:
                self.showBoardInstructions = None
            else:
                if self.gamePaused == 0:
                    self.gamePaused = 1
                    game.setMessage("Game Paused")
                else:
                    self.gamePaused = 0
                    game.setMessage("")
                    
                    
                    
    def doCheat(self):
        self.collected = self.collectedTarget
        

    def returnToMain(self):
        self.running = 0
        if highScoreCanvas.newHighScore(self.tempScore)!= -1:
            fadeManager.fadeDown(menuItems.highScoreCanvas)
        else:
            fadeManager.fadeDown(menuItems.mainScreenCanvas,1)
        #self.tempScore = 0
        

    def setUp(self,delta): 
        global oldMetaGame 
        #print "setting up game"
        self.setUpGame()
        self.newGame()
        oldMetaGame = metaGame
        fadeManager.fadeUp() 
        ScreenMessages.clearMessages() 
        self.gameOver  = 0
#        self.setUpLevel()
        self.setUpMusic()
            
            

        
    def setUpMusic(self):
        musicIndex = (self.level/5)%3
#        if musicIndex ==1:
#            self.levelSong = levelData.levelMusic3 
#        elif musicIndex ==0:
        self.levelSong = levelData.levelMusic4 
#        else:
#            self.levelSong = levelData.levelMusic2 
        if currentTunePlaying != self.levelSong[0]:
            playTuneOgg(self.levelSong[0],1)  
        
    def setUpGame(self):
        self.level = profiles[currentProfile].casualLevel
        self.levelScore = 0
        self.renderLevelScore = 0
        self.gamePaused = 0
        if arcadeMode:
            self.displayScore = self.score = profiles[currentProfile].actionScore
        elif puzzleMode:
            self.displayScore = self.score = 0
        else:
            self.displayScore = self.score = profiles[currentProfile].casualScore  
            self.lives = profiles[currentProfile].casualLives 
        self.setUpLevel()
        self.startButtonClear = 0
        self.backButtonClear = 0
        
    def nextLevel(self):
        if puzzleMode:   
            replay = 0
            if replay == 0:
                x = profiles[currentProfile].puzzleCollumn
                y = profiles[currentProfile].puzzleRow
                profiles[currentProfile].setPuzzleElementValue(x,y,1)
                self.returnToPuzzleSelection()
                return
        elif arcadeMode:
            profiles[currentProfile].actionLevel += 1  
            profiles[currentProfile].actionScore = self.score  
            self.level = profiles[currentProfile].actionLevel
        else:
            profiles[currentProfile].casualLevel += 1
            profiles[currentProfile].casualScore = self.score  
            self.level = profiles[currentProfile].casualLevel
#            if (profiles[currentProfile].casualLevel+1) % 2:
#                self.oneUp()
        self.setUpLevel()
        #self.setUpMusic()
       # self.setUpMusic()
        
        
    def doComboMessage(self,combo):  
        if(combo == 2):
            game.setMessage(messages.Combo[0])
        elif(combo == 3):
            game.setMessage(messages.SuperCombo[0])
        elif(combo == 4):
            game.setMessage(messages.MegaCombo[0])
        elif(combo == 5):
            game.setMessage(messages.UltraCombo[0])
        elif(combo > 5):
            numberCombo = str(combo-5)
            game.setMessage(messages.UltraCombo[0] + numberCombo)

    def getTimeToNextBomb(self):
        return 1 + random.randint(int(self.bombRespawnCount/4),self.bombRespawnCount)
     
    def renderLevelDebugInfo(self):
        x = 10
        y = 30
        PC.setFont(font8)
        PC.setColour(255,255,255,255)
        
        string = "bombRespawnCount: " + str(self.bombRespawnCount) 
        PC.drawString(string,x,y)
        y += 15
        string = "bombCount: " + str(self.bombCount) 
        PC.drawString(string,x,y)
        y += 15
        string = "Number Tokens: " + str(self.numberTokens) 
        PC.drawString(string,x,y)         
        y += 15
        string = "Required Number Enemies: " + str(self.requiredNumberEnemies) 
        PC.drawString(string,x,y) 
        y += 15
        string = "oneUpCount: " + str(self.oneUpCount) 
        PC.drawString(string,x,y)         


    def setUpLevel(self):
        self.doTutorial2 = 0
        self.gameOverTimer = 200
        self.levelScore = 0
        self.levelComboCount = 0
        self.longLineCount = 0
        numberLevels = len(levelData.levels)
        self.numberLevels = numberLevels
        clampedLevelNumber = self.level%numberLevels
        #clampedLevelNumber = 14
        self.checkMultiplierEnabled()
        repeatCycle = int(self.level/numberLevels)
        self.levelData = levelData.levels[clampedLevelNumber]
        numberPallets = len(palletList)
        self.pallet = palletList[self.level%numberPallets]
        self.elementColours = [self.pallet.colour1,self.pallet.colour2,self.pallet.colour3,self.pallet.colour4,self.pallet.colour5,self.pallet.colour1,self.pallet.colour2,self.pallet.colour3,self.pallet.colour4,[255,255,255]]
        self.level = profiles[currentProfile].casualLevel
        self.inEditor = 0
        self.elementGraphics = level1ElementGraphics  #currently we use the same graphics on all the levels
        self.numberTokens = self.levelData.numberTokens      
        self.numberTokens + (repeatCycle*2)
        if self.numberTokens > len(self.elementGraphics)-1:
            self.numberTokens = len(self.elementGraphics)-1

        self.showBoardInstructions = None
        self.instructionAlpha = 255
        self.levelScore= 0
        self.displayScore = self.score
        self.renderLevelScore = 0
        self.bombCount = 0
        self.oneUpCount  = 0
        self.bombRespawnCount = 0
        grid = self.levelData.gridType
        self.grid.setUpGrid(self.levelData.width,self.levelData.height,grid)
        self.rotationSpeed = self.levelData.rotationSpeed
        self.waveSpeed = self.levelData.waveSpeed
        self.waveMagnitude = self.levelData.waveMagnitude
        self.dynamicScale = self.levelData.dynamicScale
        self.oscilate = self.levelData.oscilate
        self.bombRespawnCount = int(self.levelData.bombCount * 0.8)   
        if repeatCycle:
            self.bombRespawnCount = 10 - repeatCycle
        if self.bombRespawnCount > 0:    
            self.bombCount = 1+int(self.getTimeToNextBomb() *0.5) #first time bring bomb in faster
        else:
            self.bombCount = 0
        enemies = [0]    
        self.setUpMovers(enemies)
        self.comboLevel = 0
        self.respawnTime = self.levelData.elementSpawnRate * len(self.grid.renderPathArray)
        self.respawnTime += profiles[currentProfile].scoreMultiplierEnabled*0.25  #hack to make the game a bit faster after the first tutorial has been displayed
        self.grid.setupRespawnTime()
        #print "respawn time",self.respawnTime
        self.moverSpeed = 0.6 + (math.sqrt(self.level) *.022)
        self.showDirectionIndicator = 0
        if profiles[currentProfile].scoreMultiplierEnabled==0:#hack to make the game a bit faster after the first tutorial has been displayed
            self.moverSpeed = .4
            self.showDirectionIndicator = 1
        #print "mover speed",self.moverSpeed
        self.maxMoverSpeed = self.moverSpeed * 2.5
        self.collected = 0
        self.visibleFraction  = 0
        self.fraction = 0
        self.collectedTarget = self.levelData.targetCount
        if repeatCycle:
            self.collectedTarget = 40 * repeatCycle
        self.messageString = ""
        self.messageAlpha = 0
        self.messageTime = 0
        self.exitActive = 0
        self.levelComplete = 0
        self.outOfLevel = 0
        self.levelName = self.levelData.levelName
        self.setMessage("Level "+str(self.level+1) + ":  " + self.levelName)
        self.gridAnimationTimer = 0
        self.tempScore = 0
        self.pathHint = None
        self.enemyFearcount = 0
        self.numberEnemies = 0 
        self.requiredNumberEnemies = self.levelData.requiredNumberEnemies
        self.nextEnemySpawnCounter = 0
        if repeatCycle:
            self.requiredNumberEnemies += repeatCycle * 2
        self.player.mouseDot = -1
        self.player.inputUnitX = 0
        self.player.inputUnitY = 0   
        self.bonusMultiplier = 0
        self.grid.boardAngle = 0
        if self.level%3 == 2:
            self.oneUpCount = random.randint(5,10) 
       # print "tutorial flag",self.level, profiles[currentProfile].tutorials
        if self.level == 0 and profiles[currentProfile].tutorials == 0:
            if profiles[currentProfile].inputMode==1:
                self.tutorial = tutorial.tutorial1
            else:
                self.tutorial = tutorial.Tutorial1Keys
            profiles[currentProfile].tutorials = 1
        else:
            self.tutorial = None
        if self.doTutorial2:
            self.tutorial = tutorial.tutorial2
        self.tutorialAlpha = 255
        self.tutorialFadeOut = 0
        if currentTunePlaying != levelData.menuSong:
            playTuneOgg(levelData.menuSong,1)

        
    def checkMultiplierEnabled(self):
        if profiles[currentProfile].scoreMultiplierEnabled == 0: 
            if self.level == 2:
                profiles[currentProfile].scoreMultiplierEnabled = 1
                self.doTutorial2 = 1
        
    def setUpPoem(self):
        global currentPoem
        currentPoem = None
        levelsPerPoem = 5
        poemIndex = int((self.level)%len(poem.levelPoems))
        #if poemIndex < len(poem.levelPoems):
        currentPoem =  poem.levelPoems[poemIndex]
        currentPoem.setUp()

        
    def targetReached(self):
        if self.collected < self.collectedTarget:
            return 0
        else:
            return 1
        
    def incrementComboLevel(self,increment):
        self.comboLevel += increment
        if self.comboLevel > 1:
            self.levelComboCount += 1
        if self.comboLevel == 2:
            playSimpleSound("Combo",volume = 2)
        if self.comboLevel == 3:
            playSimpleSound("SuperCombo",volume = 2)
        if self.comboLevel == 4:
            playSimpleSound("MegaCombo",volume = 2)  
        if self.comboLevel == 5:
            playSimpleSound("UltraCombo",volume = 2)             
        self.doComboMessage(self.comboLevel)
        if profiles[currentProfile].scoreMultiplierEnabled:
            self.bonusMultiplier += 1
            self.enemyFearcount = self.enemyFearcountMaximum

        
    def incrementScore(self,increment):
        oldScore = self.score
        totalIncrement = increment * (self.bonusMultiplier+1) * ((self.level*0.5)+1) * (self.comboLevel+1)* (self.comboLevel+1)
        self.score += totalIncrement
        self.levelScore += totalIncrement
        self.checkExtraLife(self.score,oldScore)
    
    def oneUp(self):
        self.lives += 1
        self.setMessage("Extra Life")
        
    scoreTargets = [
                    10000,
                    100000,
                    1000000,
                    2000000,
                    3000000,
                    4000000,
                    5000000,
                    6000000,
                    7000000,
                    8000000,
                    9000000,
                    10000000,                    
                    ]    
        
    def checkExtraLife(self,score,oldScore):
        targetScore = 1000
        #first set target score to the next threshold after the old score
        nextTarget = 0
        for target in self.scoreTargets:
            if target > oldScore and score >= target:
                self.oneUp()  
#                print "new score life",self.lives,self.score

    def incrementCollected(self,increment):
        self.collected += increment
        if self.collected > self.collectedTarget:
            self.collected = self.collectedTarget
        
    def tickDisplayScore(self,delta):
        if self.displayScore < self.score:
            scoreDelta = 0.25+((self.score - self.displayScore)/20)
            self.displayScore += scoreDelta
            if self.displayScore>self.score:
                self.displayScore = self.score
                
    def renderBonusMultiplier(self):
        string = "X"+str(int(self.bonusMultiplier))
        font = font30
        y = 500
        x = 706
        drawScoreStringVerticle(string,x,y,font)

    def renderScore(self):
        totalString = str(int(self.displayScore))# + " X"+str(int(self.bonusMultiplier))
        font = font26 
        length = len(totalString)
        lengthPixels = (length * PCR.fontAscent(font))
        y = 330 - (lengthPixels * 0.5)
         
        #PC.setColour(20,200,20,255)
        x = 760
#        string = "SCORE"
#        drawStringVerticle(string,x,y,font)
#        
#        y += 170
        alpha = 255
        game.pallet.setColourByIndex(4,alpha)   
        string = str(int(self.displayScore))
#        string += " " +str(int(self.bonusMultiplier))
        drawScoreStringVerticle(string,x,y,font)

#        PC.drawString(string,x,y)
                
    def renderLevel(self):
        font = font30
        #PC.setColour(20,200,20,255)
        alpha = 255
        game.pallet.setColourByIndex(3,alpha) 
        string = str(int(self.level)+1)
        PC.setFont(font)  
        #string = "Level:"+string
        y = 70
        x = 760
        drawScoreStringVerticle(string,x,y,font)
                
    def renderLives(self):
        font = font30
        #PC.setColour(20,200,20,255)
        alpha = 255
        game.pallet.setColourByIndex(3,alpha) 
        string = str(int(self.lives))
        PC.setFont(font)  
        #string = "Level:"+string
        y = 70
        x = 760
        drawScoreStringVerticle(string,x,y,font)
        
    def renderMultiplier(self):
        if profiles[currentProfile].scoreMultiplierEnabled: 
            font = font30
            alpha = 255
            game.pallet.setColourByIndex(3,alpha) 
            string = str(int(self.bonusMultiplier))
            PC.setFont(font)  
            y = 570
            x = 760
            fraction = game.enemyFearcount / float(game.enemyFearcountMaximum)
            if fraction < 0.4 and fraction != 0:
                range = 4+int(15 * (.4 - fraction))
                y += random.randint(0,range)
                x += random.randint(0,range)
                game.pallet.setColourByIndex(random.randint(0,4),alpha) 
            scale = 1
           # fraction = game.enemyFearcount/ float(game.enemyFearcountMaximum)
           # if fraction > .9:
           #     scale = 1 + (fraction - .9)*4
           # PCR.setFontScale(font,scale)
            drawScoreStringVerticle(string,x,y,font)
           # PCR.setFontScale(font,1)
        
    def multiplierCancelAnimation(self):
        y = 570 - 20
        x = 760 
        scale = 1
        for count in range(50):
            deltaX = .15 * (5 - random.randint(0,10))
            deltaY = 0
            x1 = x-15 + random.randint(0,30)
            y1 = y-15 + random.randint(0,30)
            particleController.addItem(numberExplosion(),x1,y1,scale,deltaX,deltaY)  
        playSimpleSound("multiplierExplosion")            

    def setMessage(self,message):
        self.messageString = message
        self.messageAlpha = 0
        self.messageTime = 0
        
    def tickMessage(self,delta):
        if self.gamePaused == 0 and self.outOfLevel == 0:
            self.messageTime += delta
        
        if self.messageTime <self.maxMessageTime:
            if self.messageAlpha < 255:
                self.messageAlpha += delta * 100
                if self.messageAlpha > 255:
                    self.messageAlpha = 255
        else:
            if self.messageAlpha > 0:
                self.messageAlpha -= delta * 3
                if self.messageAlpha < 0:
                    self.messageAlpha = 0  
                    
    def renderMessage(self):
        font = font36
        #PC.setColour(255,20,20,self.messageAlpha)   
        setPalletColour(self.pallet.colour2,self.messageAlpha)       
        string = self.messageString
        width = PCR.stringWidth(string,font)+((len(string)-1)*4)
        x = 400 - (width/2.0)
        y = 60
        PC.setFont(font)     
        for char in string:
            PC.drawString(char,x,y) 
            x += PCR.stringWidth(char,font) + 4
        
    def renderCollectedOld(self):
        font = font26
        string = str(int(self.collected))
        PC.setFont(font)  
        while len(string) < 2:
            string = "_"+string
        string = "Genes:"+string
        y = 40
        x = 20
        string2 = str(int(self.collectedTarget))
        PC.setFont(font)  
        while len(string2) < 2:  
            string2 = "_"+string2          
        string2 = " Of:"+string2 
        string = string + string2

        PC.drawString(string,x,y)        

    def renderCollected(self):
   
        x = 30
        y = 320
        width = 50
        height = 400
        top = y - height/2.0
        bottom = top + height
        res = JPG_Resources["bar1"]
        imageWidth = PCR.imageWidth(res)
        imageHeight = PCR.imageHeight(res)        
        angle = 0
        PC.setColourize(1)
        #setPalletColour(self.pallet.colour2,32)
        PC.setColour(0,0,0,64)
        PC.drawImageRotScaled( res,x- (imageWidth/2.0),y- (imageHeight/2.0),angle,2,height*1.1/imageHeight)          
        setPalletColour(self.pallet.colour1,255) 
        PC.drawImageRotScaled( res,x- (imageWidth/2.0),y- (imageHeight/2.0),angle,1,height/imageHeight)  
        numberDivisions = game.collectedTarget/5
        
        barHeight = 394
        barTop = y - barHeight/2.0
        barBottom = y + barHeight/2.0
        for division in range(1,numberDivisions):
            y1 = barTop + (barHeight * division/numberDivisions)
            angle = 22/14.0
            PC.drawImageRotScaled( res,x- (imageWidth/2.0),y1- (imageHeight/2.0),angle,.20,.20)

        barHeightNew = game.fraction * barHeight
        barHeight = game.visibleFraction * barHeight
        frequency = (2 - game.fraction) * 25.0
        alpha = 180 + (math.sin(game.gameClock/frequency)*75)
        setPalletColour(self.pallet.colour1,alpha)
        PC.drawmodeAdd()
        PC.setClipRect(0,barBottom - barHeight,800,800)
        angle = 0
        PC.drawImageRotScaled( res,x- (imageWidth/2.0),y- (imageHeight/2.0),angle,1.1,height/imageHeight)   
        PC.clearClipRect()
        PC.drawmodeNormal()
        alpha *= .6
        setPalletColour(self.pallet.colour1,alpha)
        PC.drawmodeAdd()
        PC.setClipRect(0,barBottom - barHeightNew,800,800)
        angle = 0
        PC.drawImageRotScaled( res,x- (imageWidth/2.0),y- (imageHeight/2.0),angle,1.1,height/imageHeight)   
        PC.clearClipRect()
        PC.drawmodeNormal()

    def setUpMovers(self,enemies):
        self.movers = []
        self.player = playerClass()
        self.movers.append(self.player)
        
    def checkEnemySpawn(self,delta):
        if self.nextEnemySpawnCounter:
            self.nextEnemySpawnCounter -= delta
            if self.nextEnemySpawnCounter <= 0:
                self.nextEnemySpawnCounter = 0
                self.spawnEnemy()
        elif self.numberEnemies < self.requiredNumberEnemies:
            self.nextEnemySpawnCounter = 1000

    def spawnEnemy(self):
        newMover = enemyClass()
        self.movers.append(newMover)   
        self.numberEnemies += 1       

    def clearEnemy(self):
        for mover in self.movers:
            mover.removeEnemy()
            
        
      

    def renderMovers(self):   
        for mover in self.movers:
            mover.render()
            
    def tickMovers(self,delta):
        if self.gamePaused == 0:
            for mover in self.movers:
                mover.tick(delta)
                
        if self.enemyFearcount:
           self.enemyFearcount -= delta
           if self.enemyFearcount<=0:
               self.enemyFearcount = 0
               game.multiplierCancelAnimation()
        if self.enemyFearcount == 0:
            game.bonusMultiplier = 0
            
        for mover in self.movers[:]:               
            if mover.remove ==1:
                self.movers.remove(mover)
          
game = gameClass()

def drawStringDropShadow(string,x,y,r,g,b,alpha = 255):    
        PC.drawmodeNormal()
        PC.setColour( 0, 0, 0, alpha*0.66 ) 
        PC.drawString(string, x+3, y+3) 
        PC.setColour( r, g, b, alpha )
        PC.drawString(string, x, y)
                
def renderButton(handle,x,y,upName,overName):
    res = JPG_Resources[upName]
    width = PCR.imageWidth( res )
    height = PCR.imageHeight( res )
    left = x
    right = x + width
    top = y
    bottom = y + height
    if mousex > left and mousex < right and mousey > top and mousey < bottom:
        res = JPG_Resources[overName]
    PC.setColourize(0)   
    PC.drawImage(res,x,y)
    buttonExtents[handle+"left"] = left
    buttonExtents[handle+"right"] = right
    buttonExtents[handle+"top"] = top
    buttonExtents[handle+"bottom"] = bottom
    
def renderButtonWithText(handle,x,y,upName,overName,string,font,upColour,overColour):

    res = JPG_Resources[upName]
    width = PCR.imageWidth( res )
    height = PCR.imageHeight( res )
    left = x
    right = x + width
    top = y
    bottom = y + height
    if overName != None:
        alpha = clamp255(200 + 100 * math.sin((y * .005) + (gameLife *.02)))
        if mousex > left and mousex < right and mousey > top and mousey < bottom:
            res = JPG_Resources[overName]
            PC.setColour(255,255,255,255)
        else:
            PC.setColour(200,200,200,alpha)  
        PC.setColourize(1)   
        PC.drawmodeAdd()
        PC.drawImage(res,x,y)
        PC.drawImage(res,x,y)
        PC.drawImage(res,x,y-10)    
        PC.drawmodeNormal()
    buttonExtents[handle+"left"] = left
    buttonExtents[handle+"right"] = right
    buttonExtents[handle+"top"] = top
    buttonExtents[handle+"bottom"] = bottom
    PC.setFont(font)  
    if mousex > left and mousex < right and mousey > top and mousey < bottom:
        PC.setColour(overColour[0],overColour[1],overColour[2],overColour[3])
    else:
        PC.setColour(upColour[0],upColour[1],upColour[2],upColour[3])  
    stringWidth = PCR.stringWidth(string,font)
    y1 = bottom - 20
    x1 = x + (width - stringWidth)/2.0 
    PC.drawString(string,x1,y1)
    
def renderButtonText(handle,x,y,string,font,upColour,overColour,buttonRes):
    width = PCR.stringWidth(string,font)
    height = PCR.fontAscent(font)
    left = x
    right = x + width + 40
    top = y - height
    bottom = y
    if mousex > left and mousex < right and mousey > top and mousey < bottom:
        PC.setColour(overColour[0],overColour[1],overColour[2],overColour[3])
        buttonName = buttonRes+"_over"
    else:
        PC.setColour(upColour[0],upColour[1],upColour[2],upColour[3])  
        buttonName = buttonRes+"_up"    
    buttonRes = JPG_Resources[buttonName]  
    PC.drawImage(buttonRes,x,y-height)    
    PC.setFont(font)  


    x += 40    
    PC.drawString(string,x,y)

    buttonExtents[handle+"left"] = left
    buttonExtents[handle+"right"] = right
    buttonExtents[handle+"top"] = top
    buttonExtents[handle+"bottom"] = bottom
    
def clickOnButton(handle):
    if handle+"left" in buttonExtents:
        left = buttonExtents[handle+"left"]
        right = buttonExtents[handle+"right"]
        top = buttonExtents[handle+"top"]
        bottom = buttonExtents[handle+"bottom"]
        if mousex > left and mousex < right and mousey > top and mousey < bottom:
            return 1
            
        else:
            return 0
    else:
        return 0
        
class ReverseIteratorProxy:
    def __init__(self, sequence):
        self.sequence = sequence
    def __iter__(self):
        length = len(self.sequence)
        i = length
        while i > 0:
            i = i - 1
            yield self.sequence[i]      



class element:
    x = 0
    y = 0
    res = None
    typeIndex = 0
    elementAlpha = 512
    life = 0
    alpha = 255
    teleport = None
    collectedCount = 0
    soundCount = 0
    visited = 0 #used when building
    
    def __init__(self,x,y,type):
        self.x = x
        self.y = y
        self.typeIndex = type
        nodeName = "round"
        self.bubbleRes = JPG_Resources[nodeName]
        self.connectedTo = copy.copy([])
        self.elementAlpha = random.randint(0,int(game.respawnTime)) - game.respawnTime
        self.life = 0#256 * type/float(game.numberTokens)
        
    def render(self):   
        x = self.x + game.gridXOffset
        y = self.y + game.gridYOffset
        r = game.pallet.colour4[0]
        g = game.pallet.colour4[1]
        b = game.pallet.colour4[2]   
        PC.setColour(r,g,b,self.alpha)
        PC.drawImageRotScaled( self.bubbleRes,x-10,y-10,0,0.3,0.3)  

    def renderTeleport(self,x,y): 
#        print "rendering teleport",self,self.elementAlpha
        targetWidth = 55    
        rotation = self.life/12.0
        PC.drawmodeAdd()
        name = "Hole"
        res = JPG_Resources[name] 
        imageWidth = PCR.imageWidth( res )
        x1 = x - imageWidth*0.5
        y1 = y - imageWidth*0.5
        scale = targetWidth/float(imageWidth)
        setPalletColour(game.pallet.colour4,self.elementAlpha)  
        PC.setColourize(1)
        PC.drawImageRotScaled(res,x1 ,y1,rotation,scale,scale)
        PC.drawmodeNormal()
        name = "Hole1"
        rotation = self.life/10.0
        res = JPG_Resources[name] 
        imageWidth = PCR.imageWidth( res )
        x1 = x - imageWidth*0.5
        y1 = y - imageWidth*0.5
        scale = targetWidth/float(imageWidth)
        setPalletColour(game.pallet.colour5,self.elementAlpha)  
        PC.drawImageRotScaled(res,x1 ,y1,rotation,scale,scale)
        PC.drawmodeNormal() 
        PC.setColourize(0)        
                      
    def renderBomb(self,x1,y1):  
        PC.setColourize(1)
        nodeName = "Ruby"
        res = JPG_Resources[nodeName]
        for headPart in range(8):
            colour = headPart
            if game.enemyFearcount:
                alpha = 155 + math.sin(( (headPart/8.0) * 44/7.0) + (self.life *.1)) * 100
            else:
                alpha = 155 + math.sin(( (headPart/8.0) * 44/7.0) + (self.life *.05)) * 100                              
            if self.elementAlpha < 510:
                PC.setColour(0,0,0,128) 
            else:   
                game.pallet.setColourByIndex(colour%4,alpha)  
            
            masterScale = self.elementAlpha / 510.0
            size = PCR.imageWidth(res) 
            angle = (self.life * .01) + ( (headPart/8.0) * 44/7.0)
            yDelta = math.cos(angle) * masterScale * size * .2          
            xDelta = math.sin(angle) * masterScale * size * .2
            x = x1  + xDelta
            y = y1 + yDelta
            PC.drawImageRotScaled( res,x-size/2.0,y-size/2.0,angle * -1.1,masterScale,masterScale*.25) 

                      
    def renderOneUp(self,x1,y1):  
        PC.setColourize(1)
        nodeName = "Head"
        res = JPG_Resources[nodeName]
        for headPart in range(1):
            colour = headPart
            alpha = 155 + math.sin(( (headPart/8.0) * 44/7.0) + (self.life *.05)) * 100 
            if self.collectedCount:
                alpha = 255-(self.collectedCount*5)
                alpha = clamp255(alpha)
            if self.elementAlpha < 510:
                PC.setColour(0,0,0,128) 
            else:   
                game.pallet.setColourByIndex(colour%4,alpha)  
            
            masterScale = self.elementAlpha / 510.0
            masterScale *= 1+(self.collectedCount * 0.05)
            size = PCR.imageWidth(res) 
            angle = (self.life * .01) + ( (headPart/4.0) * 44/7.0)
            xDelta = math.sin(angle) * masterScale * size * .2
            yDelta = math.cos(angle) * masterScale * size * .2          
            x = x1  + xDelta
            y = y1 + yDelta
            PC.drawImageRotScaled( res,x-size/2.0,y-size/2.0,angle*-1.25,masterScale* 0.8,masterScale*0.8) 

    def renderExit(self,x,y):
        targetWidth = 75    
        rotation = self.life/-16.0

        PC.drawmodeAdd()
        name = "Hole"
        res = JPG_Resources[name] 
        imageWidth = PCR.imageWidth( res )
        x1 = x - imageWidth*0.5
        y1 = y - imageWidth*0.5
        scale = targetWidth/float(imageWidth)
        setPalletColour(game.pallet.colour1,self.elementAlpha)  
        PC.setColourize(1)
        PC.drawImageRotScaled(res,x1 ,y1,rotation,scale,scale)
        PC.drawmodeNormal()
        name = "Hole1"
        rotation = self.life/-15.0
        res = JPG_Resources[name] 
        imageWidth = PCR.imageWidth( res )
        x1 = x - imageWidth*0.5
        y1 = y - imageWidth*0.5
        scale = targetWidth/float(imageWidth)
        setPalletColour(game.pallet.colour2,self.elementAlpha)  
        PC.drawImageRotScaled(res,x1 ,y1,rotation,scale,scale)
        PC.drawmodeNormal() 
        PC.setColourize(1)    

    def tickTeleport(self,delta):
        self.life += delta
        if self.elementAlpha <0:
            self.elementAlpha = 0
        if self.elementAlpha<255:
            self.elementAlpha += delta
            if self.elementAlpha > 255:
                self.elementAlpha = 255
                
    def tickExit(self,delta):
        self.soundCount -= delta
        if self.soundCount <= 0 and game.outOfLevel == 0:
            playSimpleSound("exitActive")  
            self.soundCount = 100   



    def tick(self,delta):
        if game.gameOver or game.outOfLevel:
            self.alpha -= delta* 4.0
            if self.alpha < 0:
                self.alpha = 0   
        return 0
                
        if self.typeIndex == 100:
            self.tickExit(delta)
        bombDuration = 1000
        if self.collectedCount:
            self.collectedCount += delta
            if self.collectedCount >= 40:
                self.typeIndex = -1
                self.collectedCount = 0
        if self.elementAlpha> 0:
            self.life += delta
            if self.typeIndex ==elements.bomb and game.enemyFearcount:
                self.life += delta * 0.5
            else:
                self.life += delta
        #if self.typeIndex ==elements.bomb:
           # if self.life > bombDuration:
           #     self.detonateBomb()
        if game.gameOver or game.outOfLevel:

            self.elementAlpha -= delta*10
            if self.elementAlpha<0:
               self.elementAlpha = 0  
        if self.teleport:
            self.tickTeleport(delta)
        elif self.typeIndex<0:
            self.typeIndex= game.getNextTypeIndex()
            self.elementAlpha = - game.respawnTime/2.0
            if self.typeIndex == elements.bomb: #if it's a bomb then we want it to appear quicker
                self.elementAlpha = 0
            self.life = 0
        else:
            if self.elementAlpha > 0 or game.targetReached()==0:
                self.elementAlpha += delta*2
                if self.elementAlpha>510:
                   self.elementAlpha = 510
                   

              

        
    def detonateBomb(self):
        self.elementAlpha = 0
        self.typeIndex = -1
        scale = 1.0
        particleController.addItem(tileExplosion(),self.x+game.gridXOffset,self.y+game.gridYOffset,scale)
        playSimpleSound("explosion2")
        
    def detonateBombFizzle(self):
        self.elementAlpha = 0
        self.typeIndex = -1
        scale = 1.0
        particleController.addItem(dustParticle(),self.x+game.gridXOffset,self.y+game.gridYOffset,scale)    
        playSimpleSound("nomore")
        
class path:
    life = 0
    alpha = 255
#    glowCount = 0
    start = None
    end = None
    unitX = 0
    unitY = 0
    originalUnitX  = 0
    originalUnitY  = 0
    angle = 0
    collectedCount = 0
    soundCount = 0
    life = 0
    validSpawn = 0
    pathLife = 0

    def __init__(self,start,end):
        self.start = start
        self.end = end
        deltaX = end.x - start.x
        deltaY = end.y - start.y
        self.length = math.sqrt((deltaX*deltaX) + (deltaY*deltaY))
        self.unitX = self.originalUnitX =  deltaX/self.length
        self.unitY = self.originalUnitY = deltaY/self.length
        self.angle = math.atan2(self.unitX,self.unitY)
        self.res = JPG_Resources["bar1"]
        self.imageHeight = PCR.imageHeight(self.res)
        self.imageWidth = PCR.imageWidth(self.res) 
       # game.getNextTypeIndex()
        self.typeIndex = game.getNextTypeIndex()
        self.elementAlpha = random.randint(0,int(game.respawnTime)) - game.respawnTime
        
    def render(self):
        startX = self.start.x + game.gridXOffset
        startY = self.start.y + game.gridYOffset
        endX = self.end.x + game.gridXOffset 
        endY = self.end.y + game.gridYOffset
        self.midX = averageX = (startX+endX)/2
        self.midY = averageY = (startY+endY)/2       
        length = self.length *1.1
        angle = self.angle
        startX1 = averageX - self.imageWidth/2.0
        startY1 = averageY - self.imageHeight/2.0
        sin = math.sin(self.pathLife/200.0)
        sin *= .0005
        alpha = clamp255(self.alpha * 250 * (.001 + sin))
        #print "alpha",self.alpha
        #alpha = self.alpha * .25
        width = 5
        PC.setColour(game.pallet.colour5[0],game.pallet.colour5[1],game.pallet.colour5[2],alpha)
        PC.drawImageRotScaled( self.res,startX1,startY1,angle,width,length/self.imageHeight)        
        PC.setColour(game.pallet.colour4[0],game.pallet.colour4[1],game.pallet.colour4[2],self.alpha)
        PC.drawImageRotScaled( self.res,startX1,startY1,angle,.5,length/self.imageHeight)  

        self.renderToken(averageX,averageY)
        

    def renderHint2(self):
        startX = game.player.x + game.gridXOffset
        startY = game.player.y + game.gridYOffset
        endX = self.end.x + game.gridXOffset
        endY = self.end.y + game.gridYOffset
        deltaX = startX - endX
        deltaY = startY - endY
        
        averageX = (startX+endX)/2
        averageY = (startY+endY)/2  
        length = math.sqrt( (deltaX * deltaX) + (deltaY * deltaY) )  * 1.1      
        width = 10
        angle = self.angle
        PC.setColourize(1)
        startX1 = averageX - self.imageWidth/2.0
        startY1 = averageY - self.imageHeight/2.0
        alpha = self.alpha * .2
        PC.drawmodeAdd()
        PC.setColour(game.pallet.colour5[0],game.pallet.colour5[1],game.pallet.colour5[2],alpha)
        PC.drawImageRotScaled( self.res,startX1,startY1,angle,5.0,length/self.imageHeight)        
        PC.setColour(game.pallet.colour4[0],game.pallet.colour4[1],game.pallet.colour4[2],self.alpha)
        PC.drawImageRotScaled( self.res,startX1,startY1,angle,.5,length/self.imageHeight) 
        PC.drawmodeNormal()
        
    def renderHint1(self):
        startX = self.start.x + game.gridXOffset
        startY = self.start.y + game.gridYOffset
        

        endX = self.end.x + game.gridXOffset 
        endY = self.end.y + game.gridYOffset
        

        averageX = (startX+endX)/2
        averageY = (startY+endY)/2        
        length = self.length *1.1
        width = 10
        angle = self.angle
        PC.setColourize(1)
        startX1 = averageX - self.imageWidth/2.0
        startY1 = averageY - self.imageHeight/2.0
        alpha = self.alpha * .2
        PC.drawmodeAdd()
        PC.setColour(game.pallet.colour5[0],game.pallet.colour5[1],game.pallet.colour5[2],alpha)
        PC.drawImageRotScaled( self.res,startX1,startY1,angle,5.0,length/self.imageHeight)        
        PC.setColour(game.pallet.colour4[0],game.pallet.colour4[1],game.pallet.colour4[2],self.alpha)
        PC.drawImageRotScaled( self.res,startX1,startY1,angle,.5,length/self.imageHeight) 
        PC.drawmodeNormal()
        
    def tick(self,delta):
        #print "path tick",self
        self.pathLife += delta 
        if game.gameOver or game.outOfLevel:
            self.alpha -= delta* 4.0
            if self.alpha < 0:
                self.alpha = 0
        if self.validSpawn:
            self.tickToken(delta)        
                

    def renderToken(self,x,y):   
        life = game.gameClock + (256 * self.typeIndex/float(game.numberTokens))
        backScale1 = (life%256)/256 * self.elementAlpha/512.0
        backScale2 = ((life+128)%256)/256  * self.elementAlpha/512.0      
        if self.typeIndex >= 0 and self.elementAlpha > 0:

            if self.typeIndex == 100:
                self.renderExit(x,y)
            elif self.typeIndex ==elements.oneUp:
                self.renderOneUp(x,y)
            elif self.typeIndex ==elements.bomb:
                self.renderBomb(x,y)
            else:
                tokenRes = JPG_Resources[game.elementGraphics[self.typeIndex]]   
                size = PCR.imageWidth(tokenRes) 
                colourIndex = self.typeIndex
                colour = game.elementColours[colourIndex]
                if self.elementAlpha < 510:
                    PC.setColour(0,0,0,128) 
                else:    
                    PC.setColour(colour[0],colour[1],colour[2],255)   
                rotation = (510 - self.elementAlpha)/200.0 + game.grid.boardAngle
                scale = self.elementAlpha/512.0
                PC.drawImageRotScaled(tokenRes,x-size/2.0,y-size/2.0,rotation,scale,scale)
                PC.drawmodeAdd()
                if self.elementAlpha >= 510:
                    colourIndex+= 1
                    if colourIndex >= len(game.elementColours):
                        colourIndex = 0
                    colour = game.elementColours[colourIndex]
                    PC.setColour(colour[0],colour[1],colour[2],(1-backScale1)*128)
                    PC.drawImageRotScaled( tokenRes,x-size/2.0,y-size/2.0,backScale1,backScale1,backScale1)
                    colourIndex += 1
                    if colourIndex >= len(game.elementColours):
                        colourIndex = 0
                    colour = game.elementColours[colourIndex]
                    PC.setColour(colour[0],colour[1],colour[2],(1-backScale2)*128)
                    PC.drawImageRotScaled( tokenRes,x-size/2.0,y-size/2.0,backScale2,backScale2,backScale2)
                PC.drawmodeNormal()      
                      
    def renderBomb(self,x1,y1):  
        PC.setColourize(1)
        nodeName = "Ruby"
        res = JPG_Resources[nodeName]
        for headPart in range(8):
            colour = headPart
            if game.enemyFearcount:
                alpha = 155 + math.sin(( (headPart/8.0) * 44/7.0) + (self.life *.1)) * 100
            else:
                alpha = 155 + math.sin(( (headPart/8.0) * 44/7.0) + (self.life *.05)) * 100                              
            if self.elementAlpha < 510:
                PC.setColour(0,0,0,128) 
            else:   
                game.pallet.setColourByIndex(colour%4,alpha)  
            
            masterScale = self.elementAlpha / 510.0
            size = PCR.imageWidth(res) 
            angle = (self.life * .01) + ( (headPart/8.0) * 44/7.0)
            yDelta = math.cos(angle) * masterScale * size * .2          
            xDelta = math.sin(angle) * masterScale * size * .2
            x = x1  + xDelta
            y = y1 + yDelta
            PC.drawImageRotScaled( res,x-size/2.0,y-size/2.0,angle * -1.1,masterScale,masterScale*.25) 

                      
    def renderOneUp(self,x1,y1):  
        PC.setColourize(1)
        nodeName = "Head"
        res = JPG_Resources[nodeName]
        for headPart in range(1):
            colour = headPart
            alpha = 155 + math.sin(( (headPart/8.0) * 44/7.0) + (self.life *.05)) * 100 
            if self.collectedCount:
                alpha = 255-(self.collectedCount*5)
                alpha = clamp255(alpha)
            if self.elementAlpha < 510:
                PC.setColour(0,0,0,128) 
            else:   
                game.pallet.setColourByIndex(colour%4,alpha)  
            
            masterScale = self.elementAlpha / 510.0
            masterScale *= 1+(self.collectedCount * 0.05)
            size = PCR.imageWidth(res) 
            angle = (self.life * .01) + ( (headPart/4.0) * 44/7.0)
            xDelta = math.sin(angle) * masterScale * size * .2
            yDelta = math.cos(angle) * masterScale * size * .2          
            x = x1  + xDelta
            y = y1 + yDelta
            PC.drawImageRotScaled( res,x-size/2.0,y-size/2.0,angle*-1.25,masterScale* 0.8,masterScale*0.8) 

    def renderExit(self,x,y):
        #print "render exit",self.life
        targetWidth = 75    
        rotation = self.life/-16.0
        PC.drawmodeAdd()
        name = "Hole"
        res = JPG_Resources[name] 
        imageWidth = PCR.imageWidth( res )
        x1 = x - imageWidth*0.5
        y1 = y - imageWidth*0.5
        scale = targetWidth/float(imageWidth)
        setPalletColour(game.pallet.colour1,self.elementAlpha)  
        PC.setColourize(1)
        PC.drawImageRotScaled(res,x1 ,y1,rotation,scale,scale)
        PC.drawmodeNormal()
        name = "Hole1"
        rotation = self.life/-15.0
        res = JPG_Resources[name] 
        imageWidth = PCR.imageWidth( res )
        x1 = x - imageWidth*0.5
        y1 = y - imageWidth*0.5
        scale = targetWidth/float(imageWidth)
        setPalletColour(game.pallet.colour2,self.elementAlpha)  
        PC.drawImageRotScaled(res,x1 ,y1,rotation,scale,scale)
        PC.drawmodeNormal()    

    def tickTeleport(self,delta):
        self.life += delta
        if self.elementAlpha <0:
            self.elementAlpha = 0
        if self.elementAlpha<255:
            self.elementAlpha += delta
            if self.elementAlpha > 255:
                self.elementAlpha = 255
                
    def tickExit(self,delta):
        self.soundCount -= delta
        if self.soundCount <= 0 and game.outOfLevel == 0:
            playSimpleSound("exitActive")  
            self.soundCount = 100   

    def tickToken(self,delta):
        if self.typeIndex == 100:
            self.tickExit(delta)
        bombDuration = 1000
        if self.collectedCount:
            self.collectedCount += delta
            if self.collectedCount >= 40:
                self.typeIndex = -1
                self.collectedCount = 0
        if self.elementAlpha> 0:
            self.life += delta
            if self.typeIndex ==elements.bomb and game.enemyFearcount:
                self.life += delta * 0.5
            else:
                self.life += delta
        if game.gameOver or game.outOfLevel:

            self.elementAlpha -= delta*10
            if self.elementAlpha<0:
               self.elementAlpha = 0  
        if self.typeIndex<0:
            self.typeIndex= game.getNextTypeIndex()
            self.elementAlpha = - game.respawnTime/2.0
            if self.typeIndex == elements.bomb: #if it's a bomb then we want it to appear quicker
                self.elementAlpha = 0
            self.life = 0
        else:
            if self.elementAlpha > 0 or game.targetReached()==0:
                self.elementAlpha += delta*2
                if self.elementAlpha>510:
                   self.elementAlpha = 510
                   
        if game.gameOver or game.outOfLevel:
            self.alpha -= delta* 4.0
            if self.alpha < 0:
                self.alpha = 0   
              

        
    def detonateBomb(self):
        self.elementAlpha = 0
        self.typeIndex = -1
        scale = 1.0
        particleController.addItem(tileExplosion(),self.midX,self.midY,scale)
        playSimpleSound("explosion2")
        
    def detonateBombFizzle(self):
        self.elementAlpha = 0
        self.typeIndex = -1
        scale = 1.0
        particleController.addItem(dustParticle(),self.midX,self.midY,scale)    
        playSimpleSound("nomore")
             
             
        
class newTrailIten:
    def __init__(self,token,currentPositionIndex):
        self.token = token
        self.currentPositionIndex = currentPositionIndex
        self.inPosition = 1
        self.size = 1
        self.x = 0
        self.y = 0
        self.rotation = 0
        tokenRes = JPG_Resources[game.elementGraphics[token]] 
        self.res = tokenRes
        self.scale = 1
        
    def addExplosion(self,count):
        scaleDelta = 0.1
        rotationDelta = 10
        #lifeDelta = 10
        lifeDelta = 30/count
        game.addParticle(self.res,self.x,self.y,self.scale,self.rotation,scaleDelta,rotationDelta,lifeDelta,1)
        thisPitch = (10 - (count*2))
        thisVolume = (count-2) * 0.25
        if game.comboLevel == 1:
            playSimpleSound("dash",volume = thisVolume,pitch = thisPitch)
        else:
            playSimpleSound("dash2",volume = thisVolume,pitch = thisPitch*0.8)

    def deathExplosion(self):
        scaleDelta = 0.04
        rotationDelta = 0
        lifeDelta = 2.5
        res = JPG_Resources["smallBoom01"]
        scale = 1
        game.addParticle(res,self.x,self.y,scale,self.rotation,scaleDelta,rotationDelta,lifeDelta,0)
     
class mover:
    x = 0
    y = 0
    res = None
    speed = 1
    masterScale = 0
    life = 0
    gameOverCount = 0
    distance = 0
    remove = 0
    
    def  convertDirectionToVector(self,direction):
        if direction == 0:
            return 1,0
        if direction == 1:
            return 0,1
        if direction == 2:
            return -1,0
        else:
            return 0,-1
            
    def getNearestPath(self,vx,vy,oldPrevNode = None):
        bestDot = -2
        bestPath = None
        for path in self.nextNode.connectedTo:
            if path.end != oldPrevNode:
                unitX = path.unitX
                unitY = path.unitY
                dot = dotProduct(vx,vy,unitX,unitY)
                distance = abs(dot - bestDot)
                if distance <.1 and oldPrevNode and self.path:
                    #print "distance less than .1"
                    bestAngle = bestPath.angle + 1000
                    newAngle = path.angle + 1000
                    currentAngle = self.path.angle + 1000
                    if newAngle < currentAngle:
                        bestDot = dot
                        bestPath = path
                else:
                    if dot > bestDot:
                        bestDot = dot
                        bestPath = path
        return bestPath 
            
    def getNearestPathNew(self,vx,vy,oldPrevNode = None):
        bestPath = None
        testAngle = math.atan2(vx,vy)
        angleDelta = 0
        for path in self.nextNode.connectedTo:
            if path.end != oldPrevNode:
                if bestPath == None:
                    bestPath = path
                    angleDelta = abs( (testAngle+100)-(path.angle+100) )
                else:
                    newAngleDelta = abs( (testAngle+100)-(path.angle+100) )
                    if newAngleDelta < angleDelta:
                        bestPath = path
                        angleDelta = newAngleDelta    
        if bestPath == None:
            print "error can't find a good path"
            bestPath = self.nextNode.connectedTo[0]
        return bestPath 

    def advancePathChoice(self):
        index = self.nextNode.connectedTo.index(game.pathHint)
        index += 1
        if index >= len(self.nextNode.connectedTo):
            index = 0
        newPath = self.nextNode.connectedTo[index]
        if newPath.end != self.prevNode:
            game.pathHint = newPath
        
        #index = self.nextNode.connectedTo.index(game.pathHint)

    def retardPathChoice(self):
        index = self.nextNode.connectedTo.index(game.pathHint)
        index -= 1
        if index <0:
            index = len(self.nextNode.connectedTo)-1
        newPath = self.nextNode.connectedTo[index]
        if newPath.end != self.prevNode:
            game.pathHint = newPath  
        
    def  getRandomDestination(self):
        self.prevNode = self.nextNode
        self.distance = 0
        numberIndex = len(self.nextNode.connectedTo)
        nextIndex = random.randint(1,numberIndex)-1
        self.path = self.prevNode.connectedTo[nextIndex]
        self.nextNode = self.path.end

    def mouseInfront(self):
        return 1  #Tony - changes this at Jarrads suggestion.
        if self.mouseDot  > -0.9:
            return 1
        else:
            return 0
            
            
    def getNextPath(self):
        if self.mouseInfront():
            testX = self.inputUnitX
            testY = self.inputUnitY
        else:
            testX = self.path.unitX
            testY = self.path.unitY              
        return self.getNearestPath(testX,testY,self.prevNode)   

    def getdefaultNextPath(self):
        if self.inputUnitX != 1000:
            testX = self.inputUnitX
            testY = self.inputUnitY
        else:
            testX = self.path.unitX
            testY = self.path.unitY              
        return self.getNearestPath(testX,testY,self.prevNode)  
        
    def doTeleport(self):
        self.distance = 0
#        print "doing teleport1",self.prevNode
        self.nextNode = self.prevNode = self.nextNode.teleport
#        print "doing teleport2",self.prevNode

    def getNextDestination(self):
        self.path = self.getNextPath()
        self.prevNode = self.nextNode
        self.oldPath = self.path 
        self.distance = 0        
        self.nextNode = self.path.end  
        self.inputUnitX = 0
        self.inputUnitY = 0
        self.mouseDot = -1
        
    def removeEnemy(self):
        return 0 #doesn't do anything for player class

        

class playerClass(mover):
    minDistance = 200
    totalRoute = []
    reducedRoute = []
    trail = []
    oldPositions = []
    deleteCount = 20
    matchFound = []

    trailSettled = 0
    removeCount = 0
    matchesFound = 0
    possibleComboRunningCount = 0
    mouseDot = 0
    segmentLength = 5.5 
    livesTrail = []
    distanceTravelled = 0
    lastTrailSaved = 0
    inputUnitX = 1000
    inputUnitY = 0
    
    
    
    def __init__(self):
        self.startNode = game.grid.getClosestCentre()
        self.prevNode = self.nextNode = self.startNode

        self.path = self.getNearestPath(0,1)
        self.nextNode = self.path.end
        self.x = self.startNode.x
        self.y = self.startNode.y
#        self.direction = direction
        nodeName = "Head"
        eyeName = "Eye"
        armorName = "Armor"
        self.res = JPG_Resources[nodeName]
        self.eyeRes = JPG_Resources[eyeName]
        self.resArmor = JPG_Resources[armorName]
        self.trail = []
        self.oldPositions = []
        self.matchFound = []
        self.gameOverCount = 0
        self.masterScale = 1
        self.eyeSize = .1
        self.distanceTravelled = 0
        self.lastTrailSaved = 0
        self.distanceBetweentTrailParts = 1
        self.nodeDone = 0
        self.nodeBackDone = 0
        self.speed = 0
        game.pathHint = self.getdefaultNextPath() 
        self.markerAlpha = 0
        self.mouseAngle = 0
        
    def loseLife(self):
        self.trailExplosion()
        game.grid.clearBombs()
        game.clearEnemy()
        game.lives -= 1
        self.clearTrail()
        self.livesExplosion()
        game.enemyFearcount = 0
        if game.lives == 0:
            if game.gameOver ==0:
                stopTuneOggComplete()
                playSimpleSound("level4Lose")    
            game.gameOver = 1
            
    def livesExplosion(self):
        for life in self.livesTrail:
            x = life[0]
            y = life[1]
            scaleDelta = 0.04
            rotationDelta = 0
            #lifeDelta = 10
            lifeDelta = 2
            res = JPG_Resources["smallBoom01"]
            scale = 1
            rotation = 0
            game.addParticle(res,x,y,scale,rotation,scaleDelta,rotationDelta,lifeDelta,0)            
        
    def clearTrail(self): 
        self.trail = []   

    def trailExplosion(self):
        for element in self.trail:
            element.deathExplosion()
            playSimpleSound("explosion4") 
        self.trail = []
        
    def mouseDown(self,button):
        self.forceRemoveMatches()
        
    def AButton(self):
        self.forceRemoveMatches()
        
    def forceRemoveMatches(self):  
        if self.removeCount:
            self.removeCount = 255
        
    def render(self):      

        self.renderTrail()  
        self.renderHead()
        self.renderMarker()
        #self.renderDebug()
       # self.debugCollisionHeadTRail()
        
    def  renderMarker(self):
        if self.nextNode:
            x = self.nextNode.x + game.gridXOffset
            y = self.nextNode.y + game.gridYOffset
            rotation = self.mouseAngle + (22/7.0)
            scale = 1
            name = "indicator"
            PC.setColourize(1)
            alpha = self.markerAlpha
            PC.setColour(255,255,255,alpha)
            if game.showDirectionIndicator==0:
                name = "indicator2"
                alpha *= 1.1
                if alpha > 255:
                    alpha = 255
                game.pallet.setColourByIndex(1,alpha) 
                scale *= 1.2
            res = JPG_Resources[name]
            size = PCR.imageWidth(res) 
            PC.drawImageRotScaled( res,x-size/2.0,y-size/2.0,rotation,scale,scale)            
            
      
        
    def renderDebug(self):
        x = 10
        y = 50
        font = font16
        PC.setFont(font)
        PC.setColour(255,255,255,255)
        string = "mouse dot "+str((int(self.mouseDot*1000))/1000.0)
        PC.drawString(string,x,y)
         
    def renderHead(self):  
        PC.setColourize(1)
        if game.enemyFearcount:
            game.pallet.setColourByIndex(3,clamp255(255-self.gameOverCount))  
            res = self.powerUpShape
            masterScale = self.masterScale *1.25
        else:
            game.pallet.setColourByIndex(2,clamp255(255-self.gameOverCount))   
            res = self.res            
            masterScale = self.masterScale
        size = PCR.imageWidth(res) 
        if self.gameOverCount:
            size += self.gameOverCount
            masterScale = self.gameOverCount
        self.renderLives(masterScale,res)
        
        if len(self.oldPositions)>4:
            coordinate = self.oldPositions[4]            
            x = coordinate[0] + game.gridXOffset
            y = coordinate[1] + game.gridYOffset 
            PC.drawImageRotScaled( res,x-size/2.0,y-size/2.0,0,.6*masterScale,.6*masterScale)
            if game.enemyFearcount:
                PC.drawmodeAdd()
                if game.enemyFearcount> game.enemyFearcountMaximum *0.4:
                    alphaFlash = 200
                else:
                   alphaFlash = clamp255(200 + (math.sin(game.gameClock*0.2)*200))
                game.pallet.setColourByIndex(3,alphaFlash)
                PC.drawImageRotScaled( res,x-size/2.0,y-size/2.0,game.gameClock*0.05,.6*masterScale,.6*masterScale) 
                self.renderLives(masterScale,res)                
                PC.drawmodeNormal()
            if game.gameOver == 0:
                coordinate = self.oldPositions[0]            
                x = coordinate[0] + game.gridXOffset
                y = coordinate[1] + game.gridYOffset 
                unitX = self.path.unitX
                unitY = self.path.unitY
                perpX = unitY
                perpY = -unitX
                eyeDistance = 5
                eye1X = x + (perpX*eyeDistance) + unitX*4
                eye1Y = y + (perpY*eyeDistance) + unitY*4
                eye2X = x - (perpX*eyeDistance) + unitX*4
                eye2Y = y - (perpY*eyeDistance) + unitY*4
                PC.drawmodeNormal() 
                eyeSize = self.eyeSize*masterScale*2
                PC.setColour(game.pallet.colour1[0],game.pallet.colour1[1],game.pallet.colour1[2],clamp255(255- self.gameOverCount))
                PC.drawImageRotScaled( self.eyeRes,eye1X-size/2.0,eye1Y-size/2.0,0,eyeSize,eyeSize)
                PC.drawImageRotScaled( self.eyeRes,eye2X-size/2.0,eye2Y-size/2.0,0,eyeSize,eyeSize)
            
    def renderLives(self,masterScale,res):         
        size = PCR.imageWidth(res) 
        numberSegments = game.lives-1   
        self.livesTrail = []
        for segment in range(numberSegments):
            index = 8+(numberSegments - segment) * self.segmentLength
            if len(self.oldPositions)>index:
                size1 = .5 + (math.sqrt(segment) * .06)
                coordinate = self.oldPositions[int(index)]            
                x = coordinate[0] + game.gridXOffset
                y = coordinate[1] + game.gridYOffset 
                self.livesTrail.append([x,y])
                PC.drawImageRotScaled( res,x-size/2.0,y-size/2.0,game.gameClock*0.05,size1*masterScale,size1*masterScale) 
             
          
    def renderTrail(self):
        index = 1
        PC.setColourize(1)
        lenTrail = len(self.trail)
        TrailRotSpeed = math.sqrt(lenTrail)*.002
        for element in self.trail:
            colour = game.elementColours[element.token]
            tokenRes = element.res  
            size = PCR.imageWidth(tokenRes)
            if size > 0:
                positionIndex = int(element.currentPositionIndex)
                positionRemainder = (element.currentPositionIndex) - positionIndex
                coordinate1 = self.oldPositions[positionIndex]
                coordinate2 = self.oldPositions[positionIndex+1]
                x = (coordinate1[0]*(1-positionRemainder)) + (coordinate2[0]*positionRemainder)+game.gridXOffset
                y = (coordinate1[1]*(1-positionRemainder)) + (coordinate2[1]*positionRemainder)+game.gridYOffset
                PC.setColour(colour[0],colour[1],colour[2],255)
                PC.drawmodeNormal() 
                if index%2:
                    rotation = self.life
                else:
                    rotation = -self.life
                    
                element.rotation = rotation
                element.scale = element.size
                element.x = x
                element.y = y
                element.colour = colour
                PC.drawImageRotScaled(tokenRes,x-size/2.0,y-size/2.0,rotation*TrailRotSpeed,element.size,element.size) 
                PC.drawImageRotScaled(tokenRes,x-size/2.0,y-size/2.0,rotation*TrailRotSpeed,element.size,element.size) 
                for match in self.matchFound:
                    if element.token == match.token:
                        alpha = clamp255(self.removeCount+20)
                        PC.setColour(255,255,255,alpha)                  
                        PC.drawmodeAdd() 
                        if profiles[currentProfile].scoreMultiplierEnabled:
                            self.powerUpShape = tokenRes
                            game.enemyFearcount = game.enemyFearcountMaximum
                        PC.drawImageRotScaled(tokenRes,x-size/2.0,y-size/2.0,rotation*TrailRotSpeed,element.size,element.size) 
                        break
            index += 1
        PC.drawmodeNormal()
        PC.setColourize(0)       

    def getNextDestination(self):
        self.path = game.pathHint
        game.pathHint = None
        self.prevNode = self.nextNode
        self.oldPath = self.path 
        self.distance = 0        
        self.nextNode = self.path.end  
        self.inputUnitX = 0
        self.inputUnitY = 0
        self.mouseDot = -1
        self.markerAlpha = 0

    def tick(self,delta):
        if game.gameOver or game.outOfLevel:
            self.markerAlpha -= delta* 4.0
            if self.markerAlpha < 0:
                self.markerAlpha = 0    
        elif self.markerAlpha < 80:
            self.markerAlpha += delta*2
        self.segmentLength = 8.3
        self.life += delta
        if game.gameOver:
            self.gameOverCount += 1
            
        if self.eyeSize > .1:
            self.eyeSize -= delta * .005
            if self.eyeSize < .1:
                self.eyeSize = .1
        maxOldPositionLength = 1000
        if profiles[currentProfile].inputMode == 0:
            buttons = getController(6)
            leftShoulder = buttons & 256
            rightShoulder = buttons & 512
            if checkKeyNoRepeat(keyMap.rightKey.keyValue) or rightShoulder: 
                #cock += 1 
                self.advancePathChoice()
            if checkKeyNoRepeat(keyMap.leftKey.keyValue) or leftShoulder: 
                #cock += 1 
                self.retardPathChoice()                
        else:
            if profiles[currentProfile].inputMode == 1:
                self.getMouseDelta()
            else:
                self.getControllerAnalogue(delta)
            #if self.distance < self.path.length *.8:
            
            #if self.mouseDot > -.99 and self.mouseDistance>10: #and self.distance < self.path.length *.75:
            game.pathHint = self.getNextPath()
                #print "changing direction"
            #print "direction",self.mouseDot,game.pathHint,self.distance
        game.currentPathHint = self.path
        if game.gameOver:
            if len(self.trail) and self.deleteCount <= 0:
                self.trail = self.trail[:-1]
                self.deleteCount = 1
            else:
                self.deleteCount -= delta
        else:
            if game.levelComplete:
                self.masterScale -= delta * .025
                if self.masterScale < 0:
                    self.masterScale = 0
                if delta>0:
                    self.oldPositions.insert(0,[self.x,self.y]) #have to do this here otherwise the trail 
                    self.oldPositions.insert(0,[self.x,self.y]) #do it twice to make trail disapear quickly
            else:
                totalLength = self.path.length
                
                deltaX = mousex - game.gridXOffset - self.x
                deltaY = mousey - game.gridYOffset - self.y
#                mouseDistance = math.sqrt(deltaX * deltaX + deltaY * deltaY)          
#                if mouseDistance < 20:
#                    targetSpeed = delta * game.getPlayerSpeed() * (mouseDistance/20.0) - 1
#                    if targetSpeed < 0:
#                        targetSpeed = 0
#                else:
                targetSpeed = game.getPlayerSpeed()
                if self.speed < targetSpeed:
                    self.speed += delta * 0.01
                    if self.speed > targetSpeed:
                        self.speed = targetSpeed
                        
                if self.speed > targetSpeed:                        
                    self.speed -= delta * 0.05
                    if self.speed < targetSpeed:
                        self.speed = targetSpeed       
                        

                #speed = delta * game.getPlayerSpeed()
                self.distance += self.speed * delta
                self.distanceTravelled += self.speed * delta
                nextNode = self.nextNode
                if nextNode.typeIndex == 100:
                    tokenSize = 0
                else:
                    tokenSize = 20
                #if self.distance > self.path.length-tokenSize and self.nodeDone == 0:
                #    self.pickUpToken()
                #    self.nodeDone= 1
                if self.distance > (self.path.length/2.0) - tokenSize and self.nodeDone == 0:
                    self.pickUpPathTokenForward()
                    self.pickUpPathTokenBack()
                    self.nodeDone= 1
                if self.distance > self.path.length:
                    if self.nextNode.teleport:
                        self.doTeleport()
                    self.nodeDone = 0
                    self.getNextDestination()  
                    if profiles[currentProfile].inputMode == 0:
                          game.pathHint = self.getdefaultNextPath()  

                if game.pathHint == None:
                    game.pathHint = self.getdefaultNextPath()   
                    #playMusicSimple("magnet")  
                self.x = self.prevNode.x + (self.path.unitX * self.distance)
                self.y = self.prevNode.y + (self.path.unitY * self.distance)
                
                if len(self.oldPositions) == 0:
                    #if the old positions are empty then stick in the current position to get us started
                    self.oldPositions.insert(0,[self.x,self.y])
                    self.lastTrailSaved = self.distanceTravelled 
                else:
                    #once we are in motion interpolate each time a point is saved to space it correctly
                    distanceDelta = self.distanceTravelled - self.lastTrailSaved
                    previousCoordinate = self.oldPositions[0] 
                    while self.distanceTravelled - self.lastTrailSaved > self.distanceBetweentTrailParts:
                        self.lastTrailSaved += self.distanceBetweentTrailParts
                        distance = self.distanceTravelled - self.lastTrailSaved
                        ratio = distance/float(distanceDelta)
                        deltaX = self.x -  previousCoordinate[0]
                        deltaY = self.y -  previousCoordinate[1]
                        saveX = previousCoordinate[0] + (deltaX * (1-ratio))
                        saveY = previousCoordinate[1] + (deltaY * (1-ratio))
                        self.oldPositions.insert(0,[saveX,saveY])
        self.tickTrail(delta)            
        
    def tickTrail(self,delta):
        if game.levelComplete == 0:
            self.checkCollisionHeadTRail()
        else:
            allOut = self.checkAtExit(delta)
            if allOut:
                if game.outOfLevel != 1:
                    playSimpleSound("levelUp",volume = 2) 
                    game.setMessage("")
                    game.setUpPoem()
                    game.outOfLevel = 1  
                    stopTuneOggComplete()
                    #if self.levelFinishedSoundPlaying == 0:
                    playSimpleSound("level4Win")                    
        if self.trailSettled:
            self.checkMatches()
        self.removeMatches()
        self.checkSpacing(delta)
        if self.trailSettled and len(self.matchFound)==0:
            self.possibleComboRunningCount -=delta
            if self.possibleComboRunningCount <=0:
                self.possibleComboRunningCount = 0
                game.comboLevel = 0
        else:
            self.possibleComboRunningCount = 10
        if self.removeCount:
            self.removeCount += delta * 1.0
            if self.removeCount > 255:
                self.removeCount = 255
        
    def checkAtExit(self,delta):
        allOut = 1
        for element in self.trail: 
            positionIndex = int(element.currentPositionIndex)
            coordinate = self.oldPositions[positionIndex]
            if coordinate[0] == self.x and coordinate[1] == self.y:
                if element.size > 0:
                    element.size -= delta * 0.025
                    if element.size <= 0:
                        element.size = 0
                        game.incrementScore(20)
                        playSimpleSound("leaveLevel") 
                    else:
                        allOut = 0
            else:
                allOut = 0
#        if allOut:
#            playSimpleSound("levelUp") 
        return allOut

    def checkSpacing(self,delta):    
        index = 0
        elementSpacing = 37
        adjustmentSpeedOut = 30.0
        adjustmentSpeedIn = 2.0
        numberSegments = game.lives-1    
        offset = (self.segmentLength*4) + (numberSegments* self.segmentLength)
        for element in self.trail: 
            targetPosition = offset + (index * elementSpacing)
            if element.currentPositionIndex < targetPosition:
                element.currentPositionIndex += delta*adjustmentSpeedOut
                if element.currentPositionIndex >= targetPosition:
                    element.currentPositionIndex = targetPosition
                    element.inPosition = 1
                    self.trailSettled = 1
                else:
                    element.inPosition = 0
                    self.trailSettled = 0                    
            elif element.currentPositionIndex > targetPosition:
                element.currentPositionIndex -= delta*adjustmentSpeedIn
                if element.currentPositionIndex <= targetPosition:
                    element.currentPositionIndex = targetPosition  
                    element.inPosition = 1
                    self.trailSettled = 1
                else:
                    element.inPosition = 0
                    self.trailSettled = 0
            else:
                self.trailSettled = 1
            index += 1        
                    
                    
    def removeMatches(self):
        if len (self.trail) > 1 and (self.trail[0].token != self.trail[1].token or self.removeCount==255): 
            count = 0
            elementExplosionList = []
            for match in self.matchFound:

                for element in self.trail[:]:
                    if element.token == match.token:
                       # element.addExplosion()
                        elementExplosionList.append(element)
                        self.trail.remove(element)
                        game.incrementCollected(1)
                        count += 1
                    else:
                        if count > 2:    
                            score = int((count) * (count) * 5)
                            game.incrementScore(score)
                            game.incrementComboLevel(1)
                            currentPoem.startLine()
                            if count > 5:
                                game.setMessage("Long Line")
                                playSimpleSound("longline",volume = 2)   
                            for element in elementExplosionList:
                                element.addExplosion(count)
                        elementExplosionList = []
                        count = 0
                if count > 2:    
                    score = int((count) * (count) * 5)
                    game.incrementScore(score)
                    game.incrementComboLevel(1)
                    currentPoem.startLine()
                    if count > 5:
                        game.setMessage("Long Line")
                        playSimpleSound("longline",volume = 2)  
                    for element in elementExplosionList:
                        element.addExplosion(count)
                elementExplosionList = []
                count = 0                        
            self.removeCount = 0
            self.matchFound = []
            self.matchesFound = 0
            self.trailSettled = 0
        
    def checkMatches(self): 
        oldMatchesFound = self.matchesFound
        self.matchesFound = 0
        self.matchFound = []
        if len(self.trail) >= 3:
            trailCopy = self.trail[:]
            matchCount = 0
            while len(trailCopy) > 1:
                if trailCopy[0].token == trailCopy[1].token:
                    matchCount += 1
                    self.matchesFound += 1
                else:
                    if matchCount >= 2:
                        self.matchFound.append(trailCopy[0])
                    matchCount = 0
                trailCopy = trailCopy[1:]
            if matchCount >= 2:
                self.matchFound.append(trailCopy[0]) 

            if oldMatchesFound < self.matchesFound:
                self.removeCount = 10   

    def checkCollisionHeadTRail(self):
        if len(self.trail)>2:
            headX = self.x
            headY = self.y
            headRadius = 10
            positionIndex = self.trail[1].currentPositionIndex     
            coordinate = self.oldPositions[int(positionIndex)]
            prevElementX = coordinate[0]
            prevElementY = coordinate[1]  
            for element in self.trail[2:]: 
                positionIndex = int(element.currentPositionIndex)
                coordinate = self.oldPositions[int(positionIndex)]                
                nextElementX = coordinate[0]
                nextElementY = coordinate[1]
                tailDeltaX = nextElementX- prevElementX
                tailDeltaY = nextElementY - prevElementY
                tailLength = math.sqrt( (tailDeltaX *tailDeltaX)  + (tailDeltaY *tailDeltaY)  )   
                midTailX = 0.5 * (nextElementX+prevElementX)
                midTailY = 0.5 * (nextElementY+prevElementY)   
                headTailDeltaX = headX - midTailX 
                headTailDeltaY = headY - midTailY                 
                headTailDistance = math.sqrt( (headTailDeltaX * headTailDeltaX)  + (headTailDeltaY * headTailDeltaY)  )   
                if headTailDistance < (tailLength * 0.5) + headRadius:
                    tailUnitX = tailDeltaX/tailLength
                    tailUnitY = tailDeltaY/tailLength
                    tailNormalX = -tailUnitY
                    tailNormalY = tailUnitX
                    distanceToLine = dotProduct(headTailDeltaX,headTailDeltaY,tailNormalX,tailNormalY)
                    distanceToLine = abs(distanceToLine)
                    if distanceToLine < headRadius * .5:
                        self.loseLife()
                        return
                prevElementX = nextElementX
                prevElementY = nextElementY
                
                
    def debugCollisionHeadTRail(self):
        if len(self.trail)>2:
            headX = self.x
            headY = self.y
            headRadius = 10
            debugCollision = 1
            positionIndex = self.trail[1].currentPositionIndex     
            coordinate = self.oldPositions[int(positionIndex)]
            prevElementX = coordinate[0]
            prevElementY = coordinate[1]  
            for element in self.trail[2:]: 
                PC.setColour(0,255,0,255)
                positionIndex = int(element.currentPositionIndex)
                coordinate = self.oldPositions[int(positionIndex)]                
                nextElementX = coordinate[0]
                nextElementY = coordinate[1]

                tailDeltaX = nextElementX- prevElementX
                tailDeltaY = nextElementY - prevElementY
                tailLength = math.sqrt( (tailDeltaX *tailDeltaX)  + (tailDeltaY *tailDeltaY)  )   
                midTailX = 0.5 * (nextElementX+prevElementX)
                midTailY = 0.5 * (nextElementY+prevElementY)   
                headTailDeltaX = headX - midTailX 
                headTailDeltaY = headY - midTailY                 
                headTailDistance = math.sqrt( (headTailDeltaX * headTailDeltaX)  + (headTailDeltaY * headTailDeltaY)  )   
                if headTailDistance < (tailLength * 0.5) + headRadius:
                    PC.setColour(255,0,0,255)
                    tailUnitX = tailDeltaX/tailLength
                    tailUnitY = tailDeltaY/tailLength
                    tailNormalX = -tailUnitY
                    tailNormalY = tailUnitX
                    distanceToLine = dotProduct(headTailDeltaX,headTailDeltaY,tailNormalX,tailNormalY)
                    if distanceToLine < headRadius:
                        PC.setColour(255,255,255,255)
                PC.drawLine(prevElementX+ game.gridXOffset,prevElementY+ game.gridYOffset,nextElementX+ game.gridXOffset,nextElementY+ game.gridYOffset)
                prevElementX = nextElementX
                prevElementY = nextElementY
            

    def pickUpToken(self):
        nextNode = self.nextNode
        if nextNode.typeIndex == 100:
            game.levelComplete = 1
            game.setMessage("Level Complete")
            playSimpleSound("leaveLevel") 
            return 
        if nextNode.elementAlpha < 510:
            return
        elif nextNode.typeIndex ==elements.bomb:
            self.pickUpBomb(nextNode)
            nextNode.typeIndex = -1
        elif nextNode.typeIndex ==elements.oneUp:
            self.pickUpOneUp(nextNode)

            #nextNode.typeIndex = -1            
        else:
            self.eyeSize = .25
            token = nextNode.typeIndex
            nextNode.typeIndex = -1
            trailPtr = newTrailIten(token,0)
            self.trail.insert(0,trailPtr)
            game.incrementScore(5)
            thisPitch = self.countSameSimbols()
            #print "thisPitch",thisPitch
            playSimpleSound("CollectToken",pitch = thisPitch) 

            

    def pickUpPathTokenForward(self):
        thisPath = self.path
        nextNode = thisPath.end
        for path in nextNode.connectedTo:
            if path.end == self.prevNode:
                self.pickUpPathToken(path)


    def pickUpPathTokenBack(self):
        thisPath = self.path
        self.pickUpPathToken(thisPath)

    def pickUpPathToken(self,thisPath):
        if thisPath.typeIndex == 100:
            game.levelComplete = 1
            game.setMessage("Level Complete")
            playSimpleSound("leaveLevel") 
            return 
        if thisPath.elementAlpha < 510:
            return
        elif thisPath.typeIndex ==elements.bomb:
            self.pickUpBomb(thisPath)
            thisPath.typeIndex = -1
        elif thisPath.typeIndex ==elements.oneUp:
            self.pickUpOneUp(thisPath)

            #nextNode.typeIndex = -1            
        else:
            self.eyeSize = .25
            token = thisPath.typeIndex
            thisPath.typeIndex = -1
            trailPtr = newTrailIten(token,0)
            self.trail.insert(0,trailPtr)
            game.incrementScore(5)
            thisPitch = self.countSameSimbols()
            #print "thisPitch",thisPitch
            playSimpleSound("CollectToken",pitch = thisPitch) 

    def countSameSimbols(self):
        count = 0
        if len(self.trail) <=1:
            return count
        head = self.trail[0]
        for nextItem in self.trail[1:]:
            if nextItem.token != head.token:
                return count
            else:
                count += 1
        return count
            
    def pickUpBomb(self,bomb):
        if game.enemyFearcount > 0:
            bomb.detonateBombFizzle()
            bombValue = 500
            game.incrementScore(bombValue)
        else:
            #game.gameOver = 1
            self.loseLife()
            bomb.detonateBomb()
           # print "collide With Player hurt",game.enemyFearcount
        
            
    def pickUpOneUp(self,oneUp):
        if oneUp.collectedCount == 0:
            game.oneUp()
            oneUp.collectedCount = 1
            playSimpleSound("extraLife")
            


            
    def getControllerAnalogue(self,delta):
        relativeMode = 1  
        controllerX = getController(2)
        controllerY = getController(3)
        minMovement = 10000
        length = math.sqrt((controllerX*controllerX) + (controllerY * controllerY))
        if length > minMovement:
            if relativeMode:
                angle = 22/7.0 - self.path.angle 
                newX= (math.cos(angle) * controllerX) + (math.sin(angle) * controllerY) 
                newY= (math.sin(angle) * controllerX) - (math.cos(angle) * controllerY) 
                controllerX = newX
                controllerY = newY              
            self.inputUnitX = controllerX  / length
            self.inputUnitY = controllerY / length
            self.mouseDot =  dotProduct(self.inputUnitX,self.inputUnitY,self.path.unitX,self.path.unitY) 
        elif self.distance < self.path.length * .5:
            self.inputUnitX = 0
            self.inputUnitY = 0
            self.mouseDot =  -1
            
    def getMouseDelta(self):
        mouseDeltaX = mousex - (self.nextNode.x + game.gridXOffset)
        mouseDeltaY = mousey - (self.nextNode.y + game.gridYOffset)
        self.mouseAngle = 0

        self.mouseDistance = math.sqrt( (mouseDeltaX*mouseDeltaX) + (mouseDeltaY * mouseDeltaY) )
        if self.mouseDistance> 0:
            self.inputUnitX = mouseDeltaX / self.mouseDistance
            self.inputUnitY = mouseDeltaY / self.mouseDistance
            self.mouseAngle = math.atan2(mouseDeltaX,mouseDeltaY)
            self.mouseDot =  dotProduct(self.inputUnitX,self.inputUnitY,self.path.unitX,self.path.unitY)
        else:
            self.inputUnitX = 0
            self.inputUnitY = 0        
            self.mouseDot = -1
        return
        if self.mouseDot <-0.5:
            mouseDeltaX = mousex - (self.x + game.gridXOffset)
            mouseDeltaY = mousey - (self.y + game.gridYOffset)   
            self.mouseDistance = math.sqrt( (mouseDeltaX*mouseDeltaX) + (mouseDeltaY * mouseDeltaY) )
            if self.mouseDistance> 0:
                self.inputUnitX = mouseDeltaX / self.mouseDistance
                self.inputUnitY = mouseDeltaY / self.mouseDistance            
                self.mouseDot =  dotProduct(self.inputUnitX,self.inputUnitY,self.path.unitX,self.path.unitY)            

        

class enemyClass(mover):
    removeTime = 50.0
    
    def __init__(self):
        self.startNode = game.grid.getEnemyStartNode()
        self.prevNode = self.nextNode = self.startNode
        self.path = None
        self.getPlayerDirection()
        self.getNextDestination()
        self.nextNode = self.path.end
        self.x = self.startNode.x
        self.y = self.startNode.y
        #self.direction = direction
        nodeName = "Ruby"
        self.res = JPG_Resources[nodeName]

        self.masterScale = 0
        self.eyeSize = .1
        self.speed = 0
        self.colours = [0,1,2,3] 
        self.remove = 0
        self.value = 5000
        self.startSequence = 0
        self.endStartSequence = 500.0
        self.maxSpeed = random.randint(90,100) * .01
#        self.path = None
        
    def tick(self,delta):

        if self.startSequence < self.endStartSequence:
            self.startSequence += delta
            if self.startSequence > self.endStartSequence:
                self.startSequence = self.endStartSequence
            self.masterScale = self.startSequence/self.endStartSequence
            
        if game.enemyFearcount:
            self.speed = game.moverSpeed * .4
            self.life += delta * -.005* game.enemyFearcount 
        else:
            self.speed = game.moverSpeed * .5
            self.life += delta
        if game.gameOver:
            self.gameOverCount += 1
        else:
            if self.remove:          
                self.masterScale += (delta * .1)
            else:
                self.masterScale += delta *.01
                if self.masterScale > 1:
                    self.masterScale = 1
        if self.remove or game.levelComplete or self.startSequence != self.endStartSequence:
            self.speed = 0
        self.moveEnemy(delta)
        if self.remove == 0 and game.levelComplete == 0 and self.startSequence == self.endStartSequence:
            #self.moveEnemy(delta)
            if self.checkCollision(delta,game.player):
                self.collideWithPlayer(game.player)
        if game.levelComplete:
            self.masterScale -= delta * 5
            if self.masterScale < 0:
                self.masterScale = 0
                
        if self.remove:
            self.remove -= delta
            if self.remove <= 1:
                self.remove = 1
            
    def mouseInfront(self):
        return 1
        
    def removeEnemy(self):    
        self.remove = self.removeTime
        game.numberEnemies -= 1      
            
    def collideWithPlayer(self,player):
        if game.enemyFearcount > 0:
           # print "collide With Player don't hurt",game.enemyFearcount
            game.incrementScore(self.value)
            self.removeEnemy()
            playSimpleSound("enemyCaught")
        else:
            #game.gameOver = 1
            player.loseLife()
            self.removeEnemy()
           # print "collide With Player hurt",game.enemyFearcount
        
    def checkCollision(self,delta,otherObject):
        deltaX = self.x - otherObject.x
        deltaY = self.y - otherObject.y
        distance = math.sqrt((deltaX * deltaX) + (deltaY * deltaY))
        collisionDistance = ((PCR.imageWidth(self.res) * self.masterScale) + (PCR.imageWidth(otherObject.res) * otherObject.masterScale)) * .5
        if collisionDistance > distance:
            return 1
        else:
            return 0
         
         
    def getNextDestination(self):
        self.path = self.getNextPath()
        self.prevNode = self.nextNode
        self.oldPath = self.path 
        self.distance = 0        
        self.nextNode = self.path.end  
        self.inputUnitX = 0
        self.inputUnitY = 0
        self.mouseDot = -1
        
    def moveEnemy(self,delta):
        self.getPlayerDirection()
        totalLength = self.path.length
        self.distance += delta * self.speed * self.maxSpeed
        nextNode = self.nextNode
        if self.distance > self.path.length:
            self.getNextDestination()
        self.x = self.prevNode.x + (self.path.unitX * self.distance)
        self.y = self.prevNode.y + (self.path.unitY * self.distance)        
        
    def getPlayerDirection(self):
        if game.enemyFearcount:
            playerDeltaX = self.nextNode.x - game.player.x
            playerDeltaY = self.nextNode.y - game.player.y
        else:
            playerDeltaX = game.player.x - self.nextNode.x
            playerDeltaY = game.player.y - self.nextNode.y

        self.playerDistance = math.sqrt( (playerDeltaX*playerDeltaX) + (playerDeltaY * playerDeltaY) )
        if self.playerDistance> 0:
            self.inputUnitX = playerDeltaX / self.playerDistance
            self.inputUnitY = playerDeltaY / self.playerDistance
        else:
            self.inputUnitX = 0
            self.inputUnitY = 0         

        
    def render(self):
        self.renderHead()
        
    def renderHead(self):  
        PC.setColourize(1)

        
        for headPart in range(4):
            colour = self.colours[headPart]
            if game.enemyFearcount:
                alpha = 76 + math.sin(( (headPart/4.0) * 44/7.0) + (self.life *.04)) * 76
            else:
                alpha = .4 * clamp255(255-(self.gameOverCount*5))
            
            if self.remove:
                alpha *= self.remove / self.removeTime                
                
            if self.startSequence < self.endStartSequence:
                PC.setColour(0,0,0,128)
                PC.drawmodeNormal()
            else:
                game.pallet.setColourByIndex(colour,alpha)
                PC.drawmodeAdd()
            


            masterScale = self.masterScale
            size = PCR.imageWidth(self.res) 
            if self.gameOverCount:
                masterScale = self.gameOverCount
                if masterScale<0:
                    masterScale = 0  
            angle = (self.life * .02) + ( (headPart/4.0) * 44/7.0)
            xDelta = math.sin(angle) * masterScale * size * .2
            yDelta = math.cos(angle) * masterScale * size * .2          
            x = self.x + game.gridXOffset + xDelta
            y = self.y + game.gridYOffset + yDelta
            PC.drawImageRotScaled( self.res,x-size/2.0,y-size/2.0,angle * -1,masterScale,masterScale*.5) 

class gridClass:
    width = 0     
    boardAngle = 0
    centreX = 0 
    centreY = 0
    minX = 0
    maxX = 0
    minY = 0
    maxY = 0
    polyList = []
    backPolyAlpha = 0
    
    def setUpGrid(self,width,height,gridType):
        self.backPolyAlpha = 0
        self.preLinked = 0
        #gridType = 14
        self.width = width
        gridPixelSize = game.gridPixelSize
        self.elementXSpacing = gridPixelSize /(6)
        self.elementYSpacing = gridPixelSize /(6)
        self.elementArray = []
        self.pathArray = []
        self.polyList = []
        self.renderPathArray = []       #as above but with no return duplicates
        if gridType == 0:
            fudge = self.setUPSquareGrid(width,height)
        elif gridType ==1 :
            fudge = self.setUPTriangleGrid(width,height)
        elif gridType == 2:
            fudge = self.setUPDiamongGrid(width,height)
        elif gridType == 3:
            fudge = self.setUPHexagonGrid(width,height)
        elif gridType == 4:
            fudge = self.setUPOctagonGrid(width,height)
        elif gridType == 5:
            fudge = self.setUPStarGrid(width,height)
        elif gridType == 6:
            fudge = self.setUPWheelGrid(width,height)
        elif gridType == 7:
            fudge = self.setUPSpiralGrid(width,height)
        elif gridType == 8:
            fudge = self.setUpSimpleWheelGrid(width,height)
#        elif gridType == 9:
#            fudge = self.setUPSpikyGrid(width,height)
        elif gridType == 9:
            fudge = self.setUPCastleGrid(width,height)
        elif gridType == 10:            
            fudge = self.setUpRingGrid(width,height)
        elif gridType == 11:            
            fudge = self.setUpMultiFiveWheelGrid(width,height)
        elif gridType == 12:            
            fudge = self.setUpBrickGrid(width,height)
        elif gridType == 13:            
            fudge = self.setUpBullsEye(width,height)
        elif gridType == 14:            
            fudge = self.setUpThreeStars(width,height)            
        self.removeBadNodes()

        if self.preLinked == 0:
            self.addLinks(fudge)
        self.sortPaths()
        self.setPathConnectCounts()
        self.centreBoard()    
        self.markValidSpawns()
        self.buildPolyList()
        

        
        
    def markValidSpawns(self):
        for path in self.renderPathArray:
            path.validSpawn = 1   
        
    def setUPSquareGridOld(self,width,height):
        for y in range(width):
            for x in range(height):
                type = game.getNextTypeIndex()
                newElement = element(x * self.elementXSpacing,y * self.elementYSpacing,type)
                self.elementArray.append(newElement)
                if x > 0:
                    newPath = path(self.elementArray[-2],newElement)
                    self.elementArray[-2].connectedTo.append(newPath)
                    self.pathArray.append(newPath)
                    newPath = path(newElement,self.elementArray[-2])
                    newElement.connectedTo.append(newPath)
                    self.pathArray.append(newPath)
                if y > 0:
                    newPath = path(self.elementArray[0-(width+1)],newElement)
                    self.elementArray[0-(width+1)].connectedTo.append(newPath)
                    self.pathArray.append(newPath)                   
                    newPath = path(newElement,self.elementArray[0-(width+1)])
                    newElement.connectedTo.append(newPath)
                    self.pathArray.append(newPath) 
        return 2

        
    def setUPSquareGrid(self,width,height):
        for y in range(width):
            for x in range(height):
                type = game.getNextTypeIndex()
                newElement = element(x * self.elementXSpacing,y * self.elementYSpacing,type)
                self.elementArray.append(newElement)
        return 2
        
    def setUpBrickGrid(self,width,height):
        self.preLinked = 1
        edgeLength = 60
        for y in range(height):
            for x in range(width):              
                type = game.getNextTypeIndex()
                newElement = element(x * edgeLength,y * edgeLength,type)
                self.elementArray.append(newElement)
                if x > 0:
                    element1 = self.elementArray[x+(y * width) ]
                    element2 = self.elementArray[x-1 + (y * width) ]
                    newPath = self.linkElements(element1,element2)
                    self.linkElements(element2,element1)
                    #only need to append the need path to the render list once
                    self.renderPathArray.append(newPath)   
                if y > 0:
                    if (x%2 and y%2)  or (x%2==0 and y%2==0) or x == 0 or x == width-1:
                        element1 = self.elementArray[x+(y * width) ]
                        element2 = self.elementArray[x+((y-1) * width) ]
                        newPath = self.linkElements(element1,element2)
                        self.linkElements(element2,element1)
                        #only need to append the need path to the render list once
                        self.renderPathArray.append(newPath)                
        return 0  


    def linkElements(self,element1,element2):    
        newPath = path(element1,element2)
        element1.connectedTo.append(newPath)
        self.pathArray.append(newPath)
        return newPath

    def setUPCastleGrid(self,width,height):
        wallList = [7,7,3,4,4,4,3,7,7]
        blockSize = 60
        x = 0
        for wall in wallList:
            y = 0
            for row in range(wall):
                type = game.getNextTypeIndex()
                newElement = element(x * blockSize,y * blockSize,type)
                self.elementArray.append(newElement)
                y -= 1
            x += 1
        #add points:
        x =  .5
        y = -7
        type = game.getNextTypeIndex()
        newElement = element(x * blockSize,y * blockSize,type)
        self.elementArray.append(newElement)
        x = 7.5
        type = game.getNextTypeIndex()
        newElement = element(x * blockSize,y * blockSize,type)
        self.elementArray.append(newElement)
        return 10

    def setUPDiamongGrid(self,width,height):
        spacing = self.elementXSpacing*1.3
        for y in range(height):
            for x in range(width + (y%2)):
                type = game.getNextTypeIndex()
                xOffset = spacing*0.5 * (y%2) 
                newElement = element(x * spacing-xOffset,y * spacing/math.sqrt(2),type)
                self.elementArray.append(newElement)
        return 1               
        
    def setUPTriangleGrid(self,width,height):
        spacingAdjuster = math.sqrt(3)/2.0
        spacing = self.elementXSpacing*1.25
        verticalSpacing = spacing*spacingAdjuster
        for y in range(height):
            for x in range(y+1):
                type = game.getNextTypeIndex()
                xOffset = -y * (spacing/2.0)
                newElement = element(x * spacing+xOffset,y * verticalSpacing,type)
                self.elementArray.append(newElement)   
        return 1
        
    def setUPHexagonGrid(self,width,height):
        spacingAdjuster = math.sqrt(3)/2.0
        spacing = self.elementXSpacing/1.3
        verticalSpacing = spacing*spacingAdjuster
        for y in range(height):
            for x in range(width):
                type = game.getNextTypeIndex()
                xOffset = y%2 * (spacing/2.0)
                if (y%2 == 0 and x%3 != 2) or (y%2 == 1 and x%3 != 1):
                    if (y == 0 and x >width-2):# or (y > height-2 and x ==0):
                        temp = 0
                    else:
                        newElement = element(x * spacing-xOffset,y * verticalSpacing,type)
                        self.elementArray.append(newElement)   
        return 1
        
        
                
    def setUPStarGrid(self,width,height):
        type = game.getNextTypeIndex()
        newElement = element(0,0,type)
        self.elementArray.append(newElement)   
        distance = 90
        for point in range(6):
            angle = (44/7.0)*point/6.0
            x = math.sin(angle)*distance
            y = math.cos(angle)*distance
            type = game.getNextTypeIndex()
            newElement = element(x,y,type)
            self.elementArray.append(newElement)   
        for point in range(6):
            angle = (44/7.0)*(point+0.5)/6.0
            distance2 = distance + (distance * (math.sqrt(3)/2.0) )
            x1 = math.sin(angle)*distance2
            y1 = math.cos(angle)*distance2
            
            angle2 = angle + (22/14.0)
            distance3 = distance 
            DX = math.sin(angle2) * distance3/2.0
            DY = math.cos(angle2) * distance3/2.0
            
            x = x1 - DX
            y = y1 - DY
            type = game.getNextTypeIndex()
            newElement = element(x,y,type)
            self.elementArray.append(newElement)   
            
            x = x1 + DX
            y = y1 + DY
            type = game.getNextTypeIndex()
            newElement = element(x,y,type)
            self.elementArray.append(newElement)   
            distance4 = distance2 + (distance * (math.sqrt(3)/2.0) )
            x = math.sin(angle2)*distance4
            y = math.cos(angle2)*distance4
            type = game.getNextTypeIndex()
            newElement = element(x,y,type)
            self.elementArray.append(newElement)               
        return 20
        
        
    def setUPWheelGrid(self,width,height):
        type = game.getNextTypeIndex()
        newElement = element(0,0,type)
        self.elementArray.append(newElement)   
        distance = 80
        for point in range(6):
            angle = (44/7.0)*point/6.0
            x = math.sin(angle)*distance
            y = math.cos(angle)*distance
            type = game.getNextTypeIndex()
            newElement = element(x,y,type)
            self.elementArray.append(newElement)   
            
        for point in range(12):
            angle = (44/7.0)*point/12.0 + (44/7.0)/24.0
            distance1 = distance * 2
            x = math.sin(angle)*distance1
            y = math.cos(angle)*distance1
            type = game.getNextTypeIndex()
            newElement = element(x,y,type)
            self.elementArray.append(newElement)           


        for point in range(18):
            angle = (44/7.0)*point/18.0 + (44/7.0)/36.0
            distance1 = distance * 3.0
            x = math.sin(angle)*distance1
            y = math.cos(angle)*distance1
            type = game.getNextTypeIndex()
            newElement = element(x,y,type)
            self.elementArray.append(newElement)    
            
        return 20
        
    def setUpSimpleWheelGrid(self,radius,numberPoints,centerX = 0,centerY = 0):
        type = game.getNextTypeIndex()
        newElement = element(centerX,centerY,type)  
        self.elementArray.append(newElement) 

        stepAngle = (44/7.0)/numberPoints 
        for point in range(numberPoints):
            angle = stepAngle * point
            distance = radius
            x =centerX + math.sin(angle) * distance
            y=centerY +  math.cos(angle) * distance
            type = game.getNextTypeIndex()
            newElement = element(x,y,type)  
            self.elementArray.append(newElement) 

        circumferance = (22/7.0) * radius * 2
        pathLength = circumferance/numberPoints
        return - pathLength * 1.5
        
    def setUpSimpleWheel(self,radius,numberPoints,centerX = 0,centerY = 0,phase=0):
        stepAngle = (44/7.0)/numberPoints 
        for point in range(numberPoints):
            angle = phase + (stepAngle * point)
            distance = radius
            x =centerX + math.sin(angle) * distance
            y=centerY +  math.cos(angle) * distance
            type = game.getNextTypeIndex()
            newElement = element(x,y,type)  
            self.elementArray.append(newElement) 

        circumferance = (22/7.0) * radius * 2
        pathLength = circumferance/numberPoints
        return - pathLength * 1.5
        
    def setUpRingGrid(self,radius,numberPoints):   
#        type = game.getNextTypeIndex()
#        newElement = element(0,0,type)  
#        self.elementArray.append(newElement) 
        self.setUpSimpleWheel(190,14,0,0)      
        self.setUpSimpleWheel(260,28,0,0)     
        return 50
        
    def setUpMultiFiveWheelGrid(self,radius,numberPoints):   
#        type = game.getNextTypeIndex()
#        newElement = element(0,0,type)  
#        self.elementArray.append(newElement) 
        self.setUpSimpleWheelGrid(80,8,150,150)  
        self.setUpSimpleWheelGrid(80,8,0,0)      
        self.setUpSimpleWheelGrid(80,8,0,300)   
        self.setUpSimpleWheelGrid(80,8,300,0)      
        self.setUpSimpleWheelGrid(80,8,300,300)           
        return 40
        
        
    def setUpBullsEye(self,radius,numberPoints): 
        self.setUpSimpleWheel(50,8,0,0)
        self.setUpSimpleWheel(100,4,0,0)          
        self.setUpSimpleWheel(150,16,0,0) 
        self.setUpSimpleWheel(200,8,0,0)         
        self.setUpSimpleWheel(250,32,0,0)  
        
        return 33    

    def setUpStar(self,size,x,y):
        self.setUpSimpleWheel(size,6,x,y,(44/7.0)/12.0)
        #ratio = 1.8
        ratio = math.sqrt(3)
        size2 = size * ratio
        #ratio = 2
        self.setUpSimpleWheel(size2,6,x,y)         
        
    def setUpThreeStars(self,radius,numberPoints): 
        radius = 55
        verticleOffset = radius * math.sqrt(3)
        self.setUpStar(radius,0,0)
        self.setUpStar(radius,radius*3,verticleOffset*-1)
        self.setUpStar(radius,radius*-3,verticleOffset*-1)
        self.setUpStar(radius,0,verticleOffset*2)
        return 10
        
    def setUPSpikyGrid(self,spokes,points):
        numberSpokes = 10.0
        pathLength = 80
        changeRadius = 300
        minRadius = 200
        stepAngle = (44/7.0)/numberSpokes 
        angle = 0
        distance = 0
        x = math.sin(angle) * distance
        y=  math.cos(angle) * distance
        type = game.getNextTypeIndex()
        newElement = element(x,y,type)
        self.elementArray.append(newElement) 
        for spoke in range(numberSpokes):
            angle = stepAngle * spoke
            
            #spokeLength = minRadius + (changeRadius * ((22/7.0 - angle) * (22/7.0 - angle)))
            spokeLength = minRadius + (math.sin(angle*4 ) * math.sin(angle*4 )  * changeRadius)
            numberPoints = spokeLength/pathLength
            for point in range(1,numberPoints):
                distance = pathLength * point
                x = math.sin(angle) * distance
                y=  math.cos(angle) * distance
                type = game.getNextTypeIndex()
                newElement = element(x,y,type)  
                self.elementArray.append(newElement)                 
        return 100             
                
    def setUPSpiralGrid(self,numberPoints,sideLength):
        stepAngle = (22/15.2)
        angle = 0
        distance = sideLength*1.5
        x = math.sin(angle) * distance
        y=  math.cos(angle) * distance
        type = game.getNextTypeIndex()
        newElement = element(x,y,type)
        self.elementArray.append(newElement) 
        for point in range(numberPoints):
            
            angleDelta = math.atan2(sideLength,distance)
            #angle += angleDelta
            newDistance = cosineRule(stepAngle,sideLength,distance)
            angleDelta = sineRuleGetAngle(stepAngle,newDistance,sideLength)
            #distance = (math.sqrt( (distance * distance) + (sideLength * sideLength) ))
            distance = newDistance
            angle += (angleDelta)
            x = math.sin(angle) * distance
            y=  math.cos(angle) * distance
            type = game.getNextTypeIndex()
            newElement = element(x,y,type)
            self.elementArray.append(newElement) 
            stepAngle += .0016
        
         
        return -72
    
    def setUPOctagonGrid(self,width,height):
        spacing1 = self.elementXSpacing/1.5
        spacing2 = spacing1 /float(math.sqrt(2.0))
        y = 0
        for yCount in range(height):
            x = 0
            for xCount in range(width):
                type = game.getNextTypeIndex()
                newElement = element(x,y,type)
                if yCount%3 == 0:
                    if xCount% 3 == 1 or xCount% 3 == 2:
                        self.elementArray.append(newElement)    
                else:
                    if xCount% 3 == 0:
                        self.elementArray.append(newElement)    
                if xCount%3 == 0 or xCount% 3 == 2:
                    x += spacing2
                else:
                    x += spacing1
            if yCount%3 == 0 or yCount%3 == 2:
                y += spacing2
            else:
                y += spacing1
        return 1   

    def centreBoard(self):
        self.minX = 100000
        self.maxX = -100000
        self.minY = 100000
        self.maxY = -100000
        totalX = 0
        totalY = 0
      
        for element in self.elementArray:    
            totalX += element.x
            totalY += element.y
            if element.x > self.maxX:
                self.maxX = element.x
            if element.x < self.minX:
                self.minX = element.x
            if element.y > self.maxY:
                self.maxY = element.y
            if element.y < self.minY:
                self.minY = element.y 
                
            element.originalX = element.x
            element.originalY = element.y
            
        self.widthPixels = self.maxX - self.minX
        self.heightPixels = self.maxY - self.minY
        self.centreX = (self.maxX + self.minX)/2.0
        self.centreY = (self.maxY + self.minY)/2.0
        self.averageX = totalX / len(self.elementArray)
        
        self.averageY = totalY / len(self.elementArray)  
        
        for element in self.elementArray:   
            element.x -= self.averageX
            element.y -= self.averageY
            element.originalX = element.x
            element.originalY = element.y
            #print "element y",element.y,self.centreY
            
        self.minX -= self.averageX
        self.minY -= self.averageY
        
        self.centreX = 0
        self.centreY = 0     
        game.gridXOffset =  game.gridXOffsetConst = (400 - (self.widthPixels/2))-self.minX      
        game.gridYOffset = game.gridYOffsetConst = 300 - (self.heightPixels/2.0)-self.minY
        
    def removeBadNodes(self):  
        for element1 in self.elementArray[:]:
            for element2 in self.elementArray[:]:
                if element1 != element2:
                    deltaX = element1.x - element2.x
                    deltaY = element1.y - element2.y
                    distance = math.sqrt((deltaX * deltaX) + (deltaY * deltaY) )
                    if distance < 1.0:
                        self.elementArray.remove(element1)
                        
    def findNextNodeC(self,nextNode,startingNode,previousNode):
        maxDistance = 100000000
        returnNode = None
        for nextPath in nextNode.connectedTo: 
            nextNextNode = nextPath.end
            deltaX = nextNextNode.x - startingNode.x
            deltaY = nextNextNode.y - startingNode.y
            distance = math.sqrt((deltaX * deltaX) + (deltaY * deltaY))
            if distance < maxDistance and nextNextNode != previousNode:
                maxDistance = distance
                returnNode = nextNextNode
        return returnNode

                        
    def buildPolyC(self,startingPath,startingNode): 
        nextNode = startingPath.end
        polyVerts = [startingNode,nextNode]
        emergency = 10
        previousNode = startingNode
        while nextNode != startingNode and emergency>0:
            emergency -= 1
            newNode = self.findNextNodeC(nextNode,startingNode,previousNode)
            if newNode:
                previousNode = nextNode
                nextNode = newNode
                if nextNode!= startingNode:
                    polyVerts.append(nextNode)
            else:
                return None
        return polyVerts
        
    def checkinPolyList(self,poly):  
        if len(self.polyList)==0:
            return 0
        for nextPoly in self.polyList:
            thisIsMatch = 1
            for vert in poly:
                if (vert in nextPoly.verts) == 0:
                    thisIsMatch = 0 
            if thisIsMatch:
                return 1
        return 0  
        
    #A-Star (but without heuristics)    

    def findShortestRoute(self,target,prevNode,nextNode,route):
        nextNode.visited = len(route)
        for path in nextNode.connectedTo:   
            nextNextNode = path.end
            if nextNextNode.visited > len(route) and nextNextNode != prevNode:
                if nextNextNode == target:
                    if self.currentRoute == None or (len(route) < len(self.currentRoute) ):
                        self.currentRoute = route
                elif len(route)<8:
                    newRoute = route + [nextNextNode]
                    self.findShortestRoute(target,nextNode,nextNextNode,newRoute)
          
    def buildPolyList(self):
        for element1 in self.elementArray:
            for path in element1.connectedTo:
                targetNode = prevNode = element1
                nextNode = path.end
                route = [prevNode,nextNode]
                for element2 in self.elementArray:
                    element2.visited = 10000
                self.currentRoute = None
                self.findShortestRoute(targetNode,prevNode,nextNode,route)
                polyVerts = self.currentRoute
                if polyVerts:
                    if self.checkinPolyList(polyVerts) == 0:
                        newPoly = polyClass(polyVerts)
                        self.polyList.append(newPoly)



    def sortPaths(self):                    
        for element1 in self.elementArray:
            element1.connectedTo.sort(self.sortAngle)
            
    def setPathConnectCounts(self):
        for element1 in self.elementArray:  
            connectedCount1 = len(element1.connectedTo)
            for path in element1.connectedTo:
                otherNode = path.end
                connectedCount2 = len(otherNode.connectedTo)
                total  = connectedCount1+connectedCount2-4
                if total < 0:
                    total = 0
                path.connectedCount = total
                #print "connected count",total
          
    def sortAngle(self,a,b):   
        aAngle = math.atan2(a.unitX,a.unitY)
        bAngle = math.atan2(b.unitX,b.unitY)
        result = int(bAngle - aAngle) 
        return result      
          
    def addLinks(self,safety):
        if safety < 0:
            minDistance = -safety
            safety = minDistance * .1
        else:
            minDistance = 100000
            for element1 in self.elementArray:
                for element2 in self.elementArray:
                    if element1 != element2:
                        deltaX = element1.x - element2.x
                        deltaY = element1.y - element2.y
                        distance = math.sqrt((deltaX * deltaX) + (deltaY * deltaY) )
                        if distance < minDistance:
                            minDistance = distance              
        for element1 in self.elementArray:
            for element2 in self.elementArray:   
                if element1 != element2:              
                    deltaX = element1.x - element2.x
                    deltaY = element1.y - element2.y
                    distance = math.sqrt((deltaX * deltaX) + (deltaY * deltaY) )
                    if distance < (minDistance + safety):
                        newPath = path(element1,element2)
                        element1.connectedTo.append(newPath)
                        self.pathArray.append(newPath)
                        if element2.connectedTo == []:  #we don't want return paths in the render list otherwise we end up rendering each path twice when we render them.
                            self.renderPathArray.append(newPath)

        previousTeleport = None
        for element in self.elementArray:
            #print "number paths",len(element.connectedTo)
            if len(element.connectedTo)==1:
                if previousTeleport == None:
                    previousTeleport = element
                else:
                    element.teleport = previousTeleport
                    previousTeleport.teleport = element
                    previousTeleport = None
                    print"adding teleport"
        if previousTeleport:
            print "uneven number of teleports"
            crash += 1
            


    def setupRespawnTime(self):
        for path in self.renderPathArray:
            path.elementAlpha = random.randint(0,int(game.respawnTime)) - game.respawnTime            
            
    def render(self):  
        PC.setColourize(1)
        PC.drawmodeNormal()
        game.pallet.setColourByIndex(0,self.backPolyAlpha)
        #print "lenght poly",len(self.polyList)
        for poly in self.polyList:
            poly.render()
 
        for path in self.renderPathArray:
            path.render()      

        for element in self.elementArray:
            element.render()
            


    def renderBack(self):
        setPalletColour(game.pallet.colour3,255)  
        PC.fillRect(self.minX+game.gridXOffset,self.minY+game.gridYOffset,self.widthPixels,self.heightPixels)
            
    def clearBombs(self):
        for path in self.renderPathArray:
            if path.typeIndex ==elements.bomb:
                path.detonateBomb()
        #game.bombCount = game.getTimeToNextBomb()
            
    def tick(self,delta):
        #print "starting tick"
        if game.gameOver or game.outOfLevel:
            self.backPolyAlpha -= delta* 1.0
            if self.backPolyAlpha<0:
                self.backPolyAlpha = 0
        else:
            self.backPolyAlpha += delta* 1.0
            if self.backPolyAlpha > 32:
                self.backPolyAlpha = 32
        game.fraction = game.collected/float(game.collectedTarget)
        if game.visibleFraction < game.fraction:
            fractionDelta = ((game.fraction - game.visibleFraction+1)*.002)
            game.visibleFraction += fractionDelta*delta
            if game.visibleFraction > game.fraction:
                game.visibleFraction = game.fraction
            #print "visibleFraction",game.fraction,game.visibleFraction,fractionDelta
        game.gridAnimationTimer += (game.fraction*delta) * .0000025
        if game.gamePaused == 0:
            for element in self.elementArray:
                element.tick(delta) 
            for path in self.renderPathArray:
                path.tick(delta)  
            if game.exitActive == 0 and game.targetReached():
                self.activateExit()
            #if game.rotationSpeed:
            self.transformBoard(delta,game.rotationSpeed,game.waveSpeed,game.dynamicScale,game.waveMagnitude,game.oscilate)   

            #if game.waveSpeed:
            #    self.waveBoard(delta,game.waveSpeed) 
           # self.adjustCentre(delta)
        return 0
        
    def adjustCentre(self,delta):
        game.gridXOffset = game.gridXOffsetConst - (game.player.x + game.gridXOffsetConst - 400)     
        game.gridYOffset = game.gridYOffsetConst - (game.player.y + game.gridYOffsetConst- 300) 
        
    def transformBoard(self,delta,rotationSpeed,waveSpeed,dynamicScale,waveMagnitude,oscilate):
        speedChange = 1
        if oscilate:
            speedChange = oscilate * math.sin(game.gameClock*oscilate)
        
        for element in self.elementArray:
            element.x = element.originalX
            element.y = element.originalY
            
        if dynamicScale:    
            for element in self.elementArray:
                oldX = element.x
                oldY = element.y
                scale = 1 + math.sin((game.gameClock)/dynamicScale) *.1
                element.x = oldX * scale 
                element.y = oldY * scale           
        if waveSpeed:
            for element in self.elementArray:
                oldX = element.x
                oldY = element.y
                element.x = oldX + (math.sin((game.gameClock + oldX)/waveSpeed)*waveMagnitude)  
                element.y = oldY + (math.cos((game.gameClock + oldY)/waveSpeed)*waveMagnitude)  

        if rotationSpeed:
            angleChange = delta*rotationSpeed*speedChange
            self.boardAngle += angleChange
            for element in self.elementArray:
                oldX = element.x
                oldY = element.y
                element.x = (math.cos(self.boardAngle) * oldX) +(math.sin(self.boardAngle) * oldY)
                element.y = (math.cos(self.boardAngle) * oldY) - (math.sin(self.boardAngle) * oldX)  

        for path in self.pathArray:
            deltaX = path.end.x - path.start.x
            deltaY = path.end.y - path.start.y
            path.length = math.sqrt((deltaX*deltaX) + (deltaY*deltaY))
            path.unitX = deltaX/path.length
            path.unitY = deltaY/path.length
            path.angle = math.atan2(path.unitX,path.unitY)
            
    def activateExit(self):
        potentialExitArray = []
        for path in self.renderPathArray:
            if path.elementAlpha < 0:
                potentialExitArray.append(path)
        if len(potentialExitArray):

            exitIndex = random.randint(0,len(potentialExitArray)-1)
            exit = potentialExitArray[exitIndex]
            if exit.validSpawn ==0:
                cock += 1
            potentialExitArray[exitIndex].typeIndex = 100
            potentialExitArray[exitIndex].elementAlpha = 10
            game.exitActive = 1
            game.setMessage("Exit Activated")
            playSimpleSound("exitActivated",volume = 2)
            
    def getEnemyStartNode(self):
        elementIDX = random.randint(0,len(self.elementArray)-1)
        
        return self.elementArray[elementIDX]
        
    def getClosestCentre(self):
        minDistance = 10000
        currentmin = None
        for element in self.elementArray:
            distance = math.sqrt( (element.x * element.x) + (element.y * element.y) )
            if distance < minDistance:
                currentmin = element
                minDistance = distance
        return currentmin
        
        
class polyClass:
    def __init__(self,verts):
        self.verts = verts
        
    def render(self):
        vertBuffer = self.verts[1:]
        x1 = self.verts[0].x + game.gridXOffset
        y1 = self.verts[0].y + game.gridYOffset
        while len( vertBuffer) >= 2: 
            if len(vertBuffer) == 2:
                x2 = vertBuffer[0].x + game.gridXOffset
                y2 = vertBuffer[0].y + game.gridYOffset
                x3 = vertBuffer[1].x + game.gridXOffset
                y3 = vertBuffer[1].y + game.gridYOffset 
                PC.drawTri(x1,y1,x2,y2,x3,y3)  
                return
            else:
                x2 = vertBuffer[0].x + game.gridXOffset
                y2 = vertBuffer[0].y + game.gridYOffset
                x3 = vertBuffer[1].x + game.gridXOffset
                y3 = vertBuffer[1].y + game.gridYOffset
                x4 = vertBuffer[2].x + game.gridXOffset
                y4 = vertBuffer[2].y + game.gridYOffset             
                PC.drawQuad(x1,y1,x2,y2,x3,y3,x4,y4)
            if len(vertBuffer)>2:
                vertBuffer = vertBuffer[2:]
            else:
                return
            
def differenceAngle(angle1,angle2):
    if angle1 < 0:
        angle1 += 44/7.0
    if angle2 < 0:
        angle2 += 44/7.0
    delta = angle1 - angle2
    if delta > 22/7.0:
        delta -= 44/7.0
    if delta < - 22/7.0:
        delta += 44/7.0  
    return delta
    
    
def dotProduct(v1X,v1Y,v2X,v2Y):
    dot = (v1X * v2X) + (v1Y * v2Y)
    return dot        
        
def drawStringCentred(string,x,y,font):
    PC.setFont(font)
    width = PCR.stringWidth(string,font)
    x -= width/2.0
    PC.drawString(string, x,y)   
    
def drawStringVerticle(string,x,y,font):
    thisY = y
    height = PCR.fontAscent(font) * 1.25
    PC.setFont(font)
    for char in string:
        width = PCR.stringWidth(char,font)
        thisX = x - (width * 0.5)
        PC.drawString(char,thisX,thisY)         
        thisY += height

def drawScoreStringVerticle(string,x,y,font):
    thisY = y
    height = PCR.fontAscent(font) * 1.0
    PC.setFont(font)
    tempString = string
    for char in string:
        #colourIndex = (len(tempString)-1)/3
        #colourIndex = (colourIndex + 2)%5
        alpha = 255
        #game.pallet.setColourByIndex(colourIndex,alpha)          
        width = PCR.stringWidth(char,font)
        thisX = x - (width * 0.5)
        PC.drawString(char,thisX,thisY)         
        thisY += height
        tempString = tempString[1:]


def drawStringRight(string,x,y,font):
    PC.setFont(font)
    width = PCR.stringWidth(string,font)
    x -= width
    PC.drawString(string, x,y) 

def drawStringLeft(string,x,y,font):
    PC.setFont(font)
    PC.drawString(string, x,y) 

def drawStringWrap(string,x,y,font,width):
    information.WrapText(string,x,y,width,font)  
    
###########################################
def getController(index):
    value = 0#PC.getController(index,0,0)
    return value
###########################################
def setMotor(motor1,motor2):
    value = PC.getController(8,motor1,motor2)        
    return value
# mouseMove
#
# Notifier called whenever the mouse moves
# inside the app window
#
###########################################

def  cosineRule(angle,d1,d2):
    cos_angle = math.cos(angle)
    value1 = cos_angle * d1 * d2*2
    value2 = (d1*d1)+(d2*d2)- value1
    value3 = math.sqrt(value2)
    return value3
    
def sineRuleGetAngle(angle1,distance1,distance2):
    value1 = math.sin(angle1)/distance1
    value2 = value1 * distance2
    angle2 = math.asin(value2)
    #if distance1 < distance2:
    #angle2 = (22/7.0) - angle2
    #print "sine rule",value1,value2
    return angle2
    
def sineRuleGetSide(angle1,distance1,angle2):
    value1 = (math.sin(angle2)/math.sin(angle1))*distance1
    return value1
