#!/usr/bin/python
#My super cool block game.
import pygame, random, math, operator, time, os, sys,pickle
from pygame.locals import *
#Constant variables or something like that...
BGCOLOR =[50,100,200] 
GRAVITY = 1



##Special functions
#Holds the informations for powerups and returns it based on number sent.
#returns pointlist, color, rect.
def iteminfo(typeno,center):
    # 0 = Nothing, 1 = Metal, 2 =  coal, 3 = water
    
    if typeno==1:
        return  [[center[0]-10,center[1]-10],[center[0]+10,center[1]-10],[center[0]+10,center[1]+10],[center[0]-10,center[1]+10]],\
               [128,128,128],\
               pygame.Rect(center[0]-10,center[1]-10,20,20)
    if typeno==2:
        return  [[center[0]-10,center[1]-10],[center[0]+10,center[1]-10],[center[0]+10,center[1]+10],[center[0]-10,center[1]+10]],\
               [28,28,28],\
               pygame.Rect(center[0]-10,center[1]-10,20,20)
    if typeno==3:
        return  [[center[0]-10,center[1]-10],[center[0]+10,center[1]-10],[center[0]+10,center[1]+10],[center[0]-10,center[1]+10]],\
               [0,75,162],\
               pygame.Rect(center[0]-10,center[1]-10,20,20)

def worldinfo(num):
    if  num[0] ==0:
        if num[1] == 0:
            if num[2] == 0:
                worldly =  [[],
                    [polygon( [80,120,80],[[500,100],[520,100],[520,140],[500,140]],1)],
                    [],
                    [],
                    [polygon( [20,40,20],[[40,100],[320,100],[320,140],[40,140]],1)],
                    [],
                    [],
                    [],
                    [],
                    [polygon( [20,40,20],[[-40,100],[-320,100],[-320,140],[-40,140]],1)],
                    [],
                    [],
                    [],
                    [],
                    [],
                    [
                        polygon( [20,40,20],[[40,100],[320,100],[320,140],[40,140]],1)\
                    ],
                    [  # Start of section 16
                        polygon( [255,255,255],[[-10,400],[620,400],[600,420],[0,420]],1),
                    polygon( [255,255,255],[[-810,390],[-10,390],[-10,420],[-810,420]],1),
                        portal([300,350],[1,0,0])
                     ],#End of section 16
                    [],
                    [],
                    [],
                    [],
                    [],
                    [],
                    [],
                    [],
                    [polygon( [20,40,20],[[40,100],[320,100],[320,140],[40,140]],1)],
                    [],
                    []]
    if  num[0] ==1:
        if num[1] == 0:
            if num[2] == 0:
                worldly = [#Sublevel 0 01 
                    [],
                    [polygon( [80,120,80],[[500,100],[520,100],[520,140],[500,140]],1)],
                    [],
                    [],
                    [polygon( [20,40,20],[[40,100],[320,100],[320,140],[40,140]],1)],
                    [],
                    [polygon( [40,60,20],[[10,100],[70,100],[70,80],[100,110],[70,140],[70,120],[10,120]],1)],
                    [],
                    [],
                    [polygon( [20,40,20],[[-40,100],[-320,100],[-320,140],[-40,140]],1)],
                    [],
                    [],
                    [],
                    [],
                    [],
                    [
                        polygon( [20,40,20],[[40,100],[320,100],[320,140],[40,140]],1)\
                    ],
                    [  # Start of section 16
                        polygon( [255,255,255],[[-10,400],[620,400],[600,420],[0,420]],1),
                    polygon( [255,255,255],[[-400,10],[-350,10],[-350,420],[-400,420]],1),
                    polygon( [255,255,255],[[-10,300],[620,300],[600,320],[0,320]],1),
                    polygon( [255,255,255],[[600,320],[620,320],[600,300],[600,320]],1),
                    polygon( [255,255,255],[[900,310],[900,310],[920,310],[920,310]],1),
                    polygon( [255,255,255],[[1000,340],[1000,310],[1030,310],[1030,340]],1),
                    polygon( [255,255,255],[[1400,410],[1400,-310],[1420,-310],[1420,410]],1),
                    polygon( [255,255,255],[[1750,310],[1750,310],[1770,310],[1770,310]],1),
                    polygon( [255,255,255],[[1525,700],[1525,50],[1526,50],[1526,700]],1),
                    polygon( [255,255,255],[[1800,510],[1800,510],[1810,510],[1810,510]],1),
                    polygon( [255,255,255],[[1570,450],[1570,-310],[1590,-310],[1590,450]],1),
                    polygon( [255,255,255],[[1910,311],[1910,311],[1915,310],[1915,310]],1),
                    platform(
                    [55,155,5],
                        [
                            [55,45],
                            [55,55],
                            [65,55],
                            [65,45]
                            ],
                        [
                            [50,50],
                            [120,300]
                            ]
                        ),
                     pest(
                        [0,0,0],
                        [
                            [55,345],
                            [55,355],
                            [65,355],
                            [65,345]
                            ],
                        [
                            [80,360],
                            [50,350],
                            [120,350]
                            ]
                        ),            
                    powerup([40,200]),
                    powerup([0,440]),
                    powerup([170,380]),
                    powerup([-380,360]),
                    powerup([570,380],0,2),
                    powerup([-170,380],0,2),
                    powerup([-70,180],0,3),
                    portal([995,280],[1,0,1])
                     ],#End of section 16
                    [],
                    [],
                    [],
                    [],
                    [],
                    [polygon( [20,40,20],[[-40,100],[-320,100],[-320,140],[-40,140]],1)],
                    [],
                    [],
                    [],
                    [],
                    [],
                    
                ]
            if num[2] == 1:
                worldly =  [[],
                    [polygon( [80,120,80],[[500,100],[520,100],[520,140],[500,140]],1)],
                    [],
                    [],
                    [polygon( [20,40,20],[[40,100],[320,100],[320,140],[40,140]],1)],
                    [],
                    [],
                    [],
                    [],
                    [polygon( [20,40,20],[[-40,100],[-320,100],[-320,140],[-40,140]],1)],
                    [],
                    [],
                    [],
                    [],
                    [],
                    [
                        polygon( [20,40,20],[[40,100],[320,100],[320,140],[40,140]],1)\
                    ],
                    [  # Start of section 16
                        polygon( [255,255,255],[[-10,400],[620,400],[600,420],[0,420]],1),
                    polygon( [255,255,255],[[-810,390],[-10,390],[-10,420],[-810,420]],1),
                    pest(
                        [0,0,0],
                        [
                            [55,345],
                            [55,355],
                            [65,355],
                            [65,345]
                            ],
                        [
                            [80,360],
                            [50,350],
                            [120,350]
                            ]
                        ),
                        pest(
                        [0,0,0],
                        [
                            [55,345],
                            [55,355],
                            [65,355],
                            [65,345]
                            ],
                        [
                            [20,360],
                            [70,250],
                            [220,350]
                            ]
                        ),       
                        plague([400,400]),
                        plague([500,400]),
                        plague([420,400]),
                        plague([400,470]),
                        plague([400,470]),
                        plague([400,470]),
                        plague([400,470]),
                        plague([400,500])
                     ],#End of section 16
                    [],
                    [],
                    [],
                    [],
                    [],
                    [],
                    [],
                    [],
                    [polygon( [20,40,20],[[40,100],[320,100],[320,140],[40,140]],1)],
                    [],
                    []]
    
    return worldly          
##People and polygons
class polygon:
    def __init__(self,color,pointlist,width=0,state=1):
        self.color = color
        self.pointlist  = pointlist
        self.width = width
        self.rect = pygame.Rect(20,20,30,30) #TODO fix!
        self.oldrect = self.rect
        self.vel = [0,0]
        self.state = state #Is it solid? yes
        self.age = 0
        self.health = 100
    def draw(self,screen):
        
        if self.width == 1:
            self.rect = pygame.draw.aalines(screen,self.color,True,self.pointlist)
        else:
            self.rect = pygame.draw.polygon(screen,self.color,self.pointlist,self.width)

    def moverel(self,x,y): #Move it an amount relative to it's position
        self.oldpointlist = self.pointlist
        self.rect = self.rect.move(x,y)
        for i in range(len(self.pointlist)):
                       self.pointlist[i][0] += x
                       self.pointlist[i][1] += y
        self.rect = self.rect.move(x,y)
                       
    def movevel(self): #Move it an amount equal to it's velocity
        self.oldpointlist = self.pointlist
        
        for i in range(len(self.pointlist)):
                       self.pointlist[i][0] += self.vel[0]
                       self.pointlist[i][1] += self.vel[1]
        self.vel[0] *= 0.9
        self.vel[1] *= 0.9
        self.rect = self.rect.move(self.vel[0],self.vel[1])

    def update(self):
        self.oldrect = self.rect

    def steamcollide(self,steamlist):
        pass
#------------------------------------------------------------------------------------------------
class person(polygon):
    def __init__(self,color,pointlist,width,state=1):
        
        self.color = color
        self.pointlist = pointlist
        #self.oldpointlist = pointlist
        self.width = width
        self.vel = [0,0]
        self.rect = pygame.Rect(20,20,30,30) #TODO fix!!!
        self.oldrect = self.rect
        self.age =0
        self.state = state
        self.items = [0,0,0,0,0,0]
        self.steam = 100
        self.steammax = 100
        self.health = 100
        self.lvlnum = [1,0,0]
        self.lvlchange = False
        self.team = 1
        self.score = 0

    def inputs(self,inputs): #Send in all the keys being pressed
        
        if (inputs.count(K_UP) >0 or inputs.count(K_w) >0)and self.steam > 0:
            self.vel[1] += -1.5
            
        if (inputs.count(K_DOWN) >0 or inputs.count(K_s) >0) and self.steam > 0:
            self.vel[1] += 0.25 
            
        if (inputs.count(K_LEFT) >0 or inputs.count(K_a) >0) and self.steam > 0:
            self.vel[0] += -1
            
        if (inputs.count(K_RIGHT) >0 or inputs.count(K_d) >0) and self.steam > 0:
            self.vel[0] += 1            
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    def collidey(self,world): #Fall down or up
        y = 0
        for i in range(len(world[16])):
            #This makes a rectangle that is really just a side of the border.
            if  self.rect.colliderect(pygame.Rect(world[16][i].rect.left + 2,world[16][i].rect.top,(world[16][i].rect.right - world[16][i].rect.left - 4),1)) :
                if world[16][i].state == 1:
                    self.vel[0] *= 0.95
                    self.vel[1] = 0
                    y = world[16][i].rect.top  - self.rect.bottom
                if world[16][i].state == 0:
                    if hasattr(world[16][i],"typeno"):
                        self.items[world[16][i].typeno] += 1
                        world[16][i].age = 100
                if hasattr(world[16][i],"pain"):
                    self.health -= world[16][i].pain
                if hasattr(world[16][i],"world"):
                    self.lvlchange = True
                    self.lvlnum =  world[16][i].world
                    
            if  self.rect.colliderect(pygame.Rect(world[16][i].rect.left + 2,world[16][i].rect.bottom,(world[16][i].rect.right - world[16][i].rect.left - 4),1)) :
                if world[16][i].state == 1:
                    self.vel[0] *= 0.95
                    self.vel[1] = 0
                    y = world[16][i].rect.bottom  - self.rect.top
                if world[16][i].state == 0:
                    if hasattr(world[16][i],"typeno"):
                        self.items[world[16][i].typeno] += 1
                        world[16][i].age = 100
                if hasattr(world[16][i],"pain"):
                    self.health -= world[16][i].pain
                if hasattr(world[16][i],"world"):
                    self.lvlchange = True
                    self.lvlnum =  world[16][i].world
        return y
    def collidex(self,world): #check for collisions. Needs polish.
        x = 0
        for i in range(len(world[16])):
            if  self.rect.colliderect(pygame.Rect(world[16][i].rect.left,world[16][i].rect.top + 2,1,(world[16][i].rect.bottom - world[16][i].rect.top - 4))) :
                if world[16][i].state == 1:
                    self.vel[0] = 0 
                    x = world[16][i].rect.left  - self.rect.right
                if world[16][i].state == 0:
                    if hasattr(world[16][i],"typeno"):
                        self.items[world[16][i].typeno] += 1
                        world[16][i].age = 100
                if hasattr(world[16][i],"pain"):
                    self.health -= world[16][i].pain
                if hasattr(world[16][i],"world"):
                    self.lvlchange = True
                    self.lvlnum =  world[16][i].world
            if self.rect.colliderect(pygame.Rect(world[16][i].rect.right,world[16][i].rect.top + 2,1,(world[16][i].rect.bottom - world[16][i].rect.top - 4))):
                if world[16][i].state == 1:
                    self.vel[0] = 0 
                    x = world[16][i].rect.right  - self.rect.left
                if world[16][i].state == 0:
                    if hasattr(world[16][i],"typeno"):
                        self.items[world[16][i].typeno] += 1
                        world[16][i].age = 100
                if hasattr(world[16][i],"pain"):
                    self.health -= world[16][i].pain
                if hasattr(world[16][i],"world"):
                    self.lvlchange = True
                    self.lvlnum =  world[16][i].world
        return x

    
#----------------------------------------------------------------------------------------
class powerup(polygon):
    def __init__(self,center,width=0,typeno=1,state=0):
        self.pointlist,self.color,self.rect = iteminfo(typeno,center)
        #self.oldpointlist = pointlist
        self.width = width
        self. vel = [0,0]
        self.typeno = typeno 
        #self.oldrect = self.rect
        self.age =0
        self.state = state # not solid.
        self.health = 100
        self.score = 2
        

#-------------------------------------------------------------------------------------------
class platform(polygon):
    def __init__(self,color,pointlist,path,speed=1,node=0,width=1,state=1):
        self.color = color
        self.pointlist  = pointlist
        self.width = width
        self.rect = pygame.Rect(100,120,30,30) #TODO fix!
        self.oldrect = self.rect
        self.vel = [0,0]
        self.state = state #Is it solid? yes
        self.age = 0
        self.path = path
        self.node =  node
        self.speed= speed
        self.health = 100

    def moverel(self,x,y): #Move it AND the track an amount relative to it's position
        self.oldpointlist = self.pointlist
        self.rect = self.rect.move(x,y)
        for i in range(len(self.pointlist)):
                       self.pointlist[i][0] += x
                       self.pointlist[i][1] += y
        for i in range(len(self.path)):
                       self.path[i][0] += x
                       self.path[i][1] += y
        self.rect = self.rect.move(x,y)

    def moveself(self,x,y): #Move it an amount relative to it's position
        self.oldpointlist = self.pointlist
        self.rect = self.rect.move(x,y)
        for i in range(len(self.pointlist)):
                       self.pointlist[i][0] += x
                       self.pointlist[i][1] += y
        self.rect = self.rect.move(x,y)

    def update(self):
        v = [\
            self.path[self.node][0] - self.rect.center[0],
            self.path[self.node][1] - self.rect.center[1]\
            ]
        magv = math.sqrt(v[0] ** 2 + v[1] ** 2)
        if magv !=0:
            unitv = [v[0] / magv,v[1] / magv]
        else:
            unitv = [0,0]
        self.moveself(unitv[0] * self.speed,unitv[1] * self.speed)
        
        if  abs(self.path[self.node][0] - self.rect.center[0]) <= self.speed and\
                abs(self.path[self.node][1] - self.rect.center[1]) <= self.speed:
            self.node = (self.node + 1) % len(self.path)
        
    

#------------------------------------------------------------------------------------------
class pest(platform):
    def __init__(self,color,pointlist,path,speed=1,node=0,width=0,state=0,pain=0.2,health=25):
        self.color = color
        self.pointlist  = pointlist
        self.width = width
        self.rect = pygame.Rect(100,120,30,30) #TODO fix!
        self.oldrect = self.rect
        self.vel = [0,0]
        self.state = state #Is it solid? yes
        self.age = 0
        self.path = path
        self.node =  node
        self.speed= speed
        self.pain = pain
        self.health = health
        self.team = 0
        self.score = 5

    def steamcollide(self,steamlist):
        for steambot in steamlist:
            
            if (steambot.center[0] - self.rect.center[0]) ** 2 + (steambot.center[1] -self.rect.center[1] ** 2) <= steambot.radius ** 2 and steambot.team != self.team:
                self.health -= steambot.pain / steambot.age
                

##########################   
#Particles or as close as I can get#
##########################    

class particle:
    def __init__(self,center,color=[210, 225, 245],radius=5, width=0, pain = 0,team=1):
        self.center = center
        #self.brightness = brightness + random.randint(-5,15)
        self.radius = radius
        self.color = color
        self.width = width
        self.age = 0
        self.rect = pygame.Rect(self.center[0] - radius, self.center[1] - radius,2 * radius, 2 * radius)
        self.oldrect = self.rect
        self.health = 100
        self.pain = pain
        self.team = team
        self.score = 0
        
    def draw(self,screen):
        
        self. rect = \
              pygame.draw.circle\
              (screen,
               [int(self.color[0]) ,int( self.color[1]) ,int( self.color[2])],
               [int(self.center[0]),int(self.center[1])],
                 self.radius,
                 self.width)

    def moverel(self,x,y):
        self.center[0] += x
        self.center[1] += y
        self.rect = self.rect.move(x,y)

    def update(self):
        #if self.brightness > 2:
         #   self.brightness  -= 2
        self.color = [
            (self.color[0] + 0.06 * (BGCOLOR[0] - self.color[0])),
                      (self.color[1] + 0.06 * (BGCOLOR[1] - self.color[1])),
                      (self.color[2] + 0.06 * (BGCOLOR[2] - self.color[2])),
                      ]
        self.radius += 1
        self.age += 1
        self.oldrect = self.rect
    def steamcollide(self,steamlist):
        pass
        
        
#---------------------------------------------------------------------------------------

class portal(particle):
    def __init__(self,center,world,color=[200,200,100],radius=20, width=0):
        self.center = center
        
        self.radius = radius
        self.color = color
        self.oldcolor = color
        self.width = width
        self.age = 0
        self.rect = pygame.Rect(self.center[0] - radius, self.center[1] - radius,2 * radius, 2 * radius)
        self.oldrect = self.rect
        self.world = world
        self.state = 0
        self.flip = 1
        self.health = 100

    def update(self):
        if self.flip == 1:
            self.color = [
            (self.color[0] +  0.06 * (BGCOLOR[0] - self.color[0])),
                      (self.color[1] +  0.06 * (BGCOLOR[1] - self.color[1])),
                      (self.color[2] +  0.06 * (BGCOLOR[2] - self.color[2])),
                      ]
        else:
            self.color = [
            (self.color[0] +  0.06 * (self.oldcolor[0] - self.color[0])),
                      (self.color[1] +  0.06 * (self.oldcolor[1] - self.color[1])),
                      (self.color[2] +  0.06 * (self.oldcolor[2] - self.color[2])),
                      ]

        self.age += 0.025
        if self.age >3:
            self.flip *= -1
            self.age = 0
        
        
        
        
        self.oldrect = self.rect
  #---------------------------------------------------------------------------------------------
class plague(particle):
    def __init__(self,center,color=[120, 30, 75],radius=3, width=0, pain = 0.03,team=0,speed = 2.5):
        self.center = center
        #self.brightness = brightness + random.randint(-5,15)
        self.radius = radius
        self.color = color
        self.width = width
        self.age = 0
        self.rect = pygame.Rect(self.center[0] - radius, self.center[1] - radius,2 * radius, 2 * radius)
        self.oldrect = self.rect
        self.health = 100
        self.pain = pain
        self.team = team
        self.vel = [0,0]
        self.v = [0,0]
        self.speed = speed
        self.state = 0
        self.score = 10
    
    def steamcollide(self,steamlist):
        self.v = self.vel[:]
        for steambot in steamlist:
            
            if steambot.team != self.team and steambot.age < 30:
                self.v[0] += (steambot.center[0] - self.center[0]) * 10 * cmp(0.0001,steambot.pain) / steambot.age / (abs(steambot.center[0] - self.center[0])+0.001)
                self.v[1] += (steambot.center[1] - self.center[1]) * 10 * cmp(0.0001,steambot.pain) / steambot.age / (abs(steambot.center[1] - self.center[1])+0.001)
                if (steambot.center[0] - self.center[0]) ** 2 + (steambot.center[1] - self.center[1] ** 2) <= steambot.radius ** 2 :
                    self.health -= steambot.pain / steambot.age

    def playerseek(self,player):
        self.v[0] += 2 *(player.rect.center[0] - self.rect.center[0]) / (abs(player.rect.center[0] - self.rect.center[0])+0.001) 
        self.v[1] += 2 *(player.rect.center[1] - self.rect.center[1]) / (abs(player.rect.center[1] - self.rect.center[1])+0.001)
        
        
       

    def hive(self,world):
        for bug in world:
            if bug.__class__.__name__ == "plague":
                if  abs((bug.center[0] - self.center[0])) < 10:
                    self.v[0] -= (bug.center[0] - self.center[0]) / (abs(bug.center[0] - self.center[0])+0.001)
                else:
                    self.v[0] += (bug.center[0] - self.center[0]) / (abs(bug.center[0] - self.center[0])+0.001)
                if  abs((bug.center[0] - self.center[0])) < 10:
                    self.v[1] -= (bug.center[1] - self.center[1]) / (abs(bug.center[1] - self.center[1])+0.001)
                else:
                     self.v[1] += (bug.center[1] - self.center[1]) /(abs(bug.center[1] - self.center[1])+0.001)

            if self.center[0] < 0:
                self.vel[0] = abs(self.vel[0] * 0.4  )
            if self.center[0] > 640:
                self.vel[0] = -abs(self.vel[0] * 0.4 )
            if self.center[1] < 0:
                self.vel[1] = abs(self.vel[1] * 0.4 )
            if self.center[1] > 480:
                self.vel[1] = -abs(self.vel[0] * 0.4 )
        magv = math.sqrt(self.v[0] ** 2 + self.v[1] ** 2)
        if magv !=0:
            unitv = [self.v[0] / magv,self.v[1] / magv]
        else:
            unitv = [0,0]
        self.vel[0] *= 0.8
        self.vel[1] *= 0.8
        self.vel[0] += unitv[0]
        self.vel[1] += unitv[1]
        self.moverel(self.vel[0] * self.speed,self.vel[1] * self.speed)
        
    def update(self):
        pass
        
        
        


############################
#This where all the magic happens!#
############################
class sSave:
    """A class for tracking high scores."""
    def __init__(self):
        self.readFile()
        filename = os.path.join("save.txt")
        save = open(filename, "r")
        self.theList = pickle.load(save)
        save.close()
        
    def readFile(self):
        filename = os.path.join("save.txt")
        try:
            save = open(filename, "r")
            self.theList = pickle.load(save)
            save.close()
        except IOError:
            print "Oops! I can't seem to find a saved game!"
            print "Creating a new one..."
            self.createNew()
            print "New save list created."

    def loadFile(self):
        return self.theList
    
    def addScore(self, player,world):
        

        self.theList = (player,world)
            
    def createNew(self):
        self.theList = (person([100,200,200],
                     [[110,200],[140,200],[140,230],[110,230]],
                     0),worldinfo([0,0,0]))
        #              
        #
        self.writeFile()
    
    def writeFile(self):
        filename = os.path.join("save.txt")
        try:
            save = open(filename, "w")
            pickle.dump(self.theList, save)
            save.close()
        except IOError:
            print "Oops! Can't create new save file!"
            raise SystemExit




    
def main():
    #Screen setup
    pygame.init()
    #BGCOLOR =[50,100,200] 
    screen = pygame.display.set_mode([640, 480],0,32)
    screen.fill(BGCOLOR)
    pygame.display.update()
    #Clock init
    clock = pygame.time.Clock()
    #Keylists init.
    #  #
    downlist = []
    uplist = []
    pressedlist = []
    ##################
    #Player and world init#
    ##################
    hud = [polygon([200,200,200],[[0,0],[0,50],[20,50],[20,0]],0,0),
           
           polygon([20,20,20],[[0,0],[0,50],[20,50],[20,0]],2,0),
           polygon([200,50,50],[[628,0],[628,50],[640,50],[640,0]],0,0),
           
           polygon([20,20,20],[[626,0],[626,50],[638,50],[638,0]],2,0)]
    
    #player = person([100,200,200],
    #                 [[200,200],[230,200],[230,230],[200,230]],
     #                0)



    
    world = worldinfo([1,0,0])
    steamlist = []
    
    #############
    #other stuff
    #############
    delay = 0
    delayb = 0
    level = sSave()
    
    player,world = level.loadFile()
    
    player.lvlchange = False
    #player.lvlnum = [0,0,0]
    loaded = False
    while True:
        
        if player.health <= 0:
            
            
            if player.lvlnum[2] > 0:
                
                player.lvlnum = [player.lvlnum[0],player.lvlnum[1],player.lvlnum[2]-1]
                
            elif player.lvlnum[1] > 0:
                
                player.lvlnum = [player.lvlnum[0],player.lvlnum[1]-1,player.lvlnum[2]]
                
            elif player.lvlnum[0] != 0:
                print player.lvlnum
                player.lvlnum[0] -= 1
            else:
                
                world = worldinfo([0,0,0])
           
                
            
               
                
            

        if loaded:
            world = worldinfo([player.lvlnum[0],player.lvlnum[1],player.lvlnum[2]])
        else:
            loaded = True
        if player.health <= 0:
            player = person([100,200,200],[[200,200],[230,200],[230,230],[200,230]],0)
        player.lvlchange = False
        #BGCOLOR =[50-10*player.lvlnum[0],100-20*player.lvlnum[1],200-40*player.lvlnum[2]] 
        #The actual loop.
        while player.health > 0 and player.lvlchange == False:
            #Wiping variables, ticking clock, clearing screen
            clock.tick(40)
            screen.fill(BGCOLOR)
            delay += 1
            delayb += 1
            downlist = []
            uplist = []
    
            #Steam!
            if True :#delay > 0:
                #delay = 0
                if player.steam > 0.5:
                    if pressedlist.count(K_UP) >0 or pressedlist.count(K_w) >0:
                        if pressedlist.count(K_x) >0 or pressedlist.count(K_LCTRL) >0 or pressedlist.count(K_RCTRL) >0 or pressedlist.count(K_RETURN) >0 or pressedlist.count(K_SPACE) >0:
                            steamlist.append(particle([player.rect.center[0],player.rect.bottom],[5,5,5],5,0,0.03,1))
                            player.steam -= 1.3
                        else:
                            steamlist.append(particle([player.rect.center[0],player.rect.bottom]))
                            player.steam -= 1.1
                        
                        
                    if pressedlist.count(K_DOWN) >0 or pressedlist.count(K_s) >0:
                        if pressedlist.count(K_x)>0 or pressedlist.count(K_LCTRL) >0 or pressedlist.count(K_RCTRL) >0 or pressedlist.count(K_RETURN) >0 or pressedlist.count(K_SPACE) >0:
                            steamlist.append(particle([player.rect.center[0],player.rect.top],[5,5,5],5,0,0.03,1))
                            player.steam -= 1.3
                        else:
                            steamlist.append(particle([player.rect.center[0],player.rect.top]))
                            player.steam -= 1.1
                    if pressedlist.count(K_LEFT) >0 or pressedlist.count(K_a) >0 :
                        if pressedlist.count(K_x)>0 or pressedlist.count(K_LCTRL) >0 or pressedlist.count(K_RCTRL) >0 or pressedlist.count(K_RETURN) >0 or pressedlist.count(K_SPACE) >0:
                            steamlist.append(particle([player.rect.right,player.rect.center[1]],[5,5,5],5,0,0.03,1))
                            player.steam -= 1.3
                        else:
                            steamlist.append(particle([player.rect.right,player.rect.center[1]]))
                            player.steam -= 1.1
                    if pressedlist.count(K_RIGHT) >0 or pressedlist.count(K_d) >0:
                        if pressedlist.count(K_x)>0 or pressedlist.count(K_LCTRL) >0 or pressedlist.count(K_RCTRL) >0 or pressedlist.count(K_RETURN) >0 or pressedlist.count(K_SPACE) >0:
                            steamlist.append(particle([player.rect.left,player.rect.center[1]],[5,5,5],5,0,0.03,1))
                            player.steam -= 1.3
                        else:
                            steamlist.append(particle([player.rect.left,player.rect.center[1]]))
                            player.steam -= 1.1
            for i in range(5):
                if len(steamlist) > 0:
                    if steamlist[0].age > 80:
                        del steamlist[0]
            for steambot in steamlist:
                steambot.update()
                steambot.draw(screen)
    
            #What a brave new WORLD.
    
                    
                     
                   
            for i in range(len(world)):
                for j in range(len(world[i])):
                    
                    world[i][j].update()
                    world[i][j].steamcollide(steamlist)
                    if  hasattr(world[i][j],"hive"):
                        world[i][j].playerseek(player)
                        world[i][j].hive(world[16][:])
                    
                    if i <= 16:
                        world[i][j].draw(screen)
            
            for i in range(len(world)):
                if len(world[i]) > 0:
                    for j in range(len(world[i])):
                        if world[i][-j].age > 90 or world[i][-j].health <= 0:
                                del world[i][-j]
    
                        
                    
    
            
            
            #Now why would you want to quit?    
            for key in pygame.event.get(QUIT):
                 pygame.display.quit()
                 return
            #Add key presses to respective lists.
            for key in pygame.event.get(KEYUP):
                uplist.append(key.key)
                pressedlist = [item for item in pressedlist if  item != key.key]            
            for key in pygame.event.get(KEYDOWN):
                downlist.append(key.key)
                pressedlist.append(key.key)
    
            
                
            for key in pressedlist:
                if key == K_ESCAPE:
                    level.addScore(player,world)
                    level.writeFile()
                    pygame.display.quit()
                    
                    
                    
                    return
            ###################
            #player and world stuff.#
            ###################
            
            player.update()
            player.inputs(pressedlist)
            
            player.vel[1] += GRAVITY
            player.vel[0]  *= 0.9
            player.movevel()       
            player.color = [200,200,100]
            player.moverel(0,player.collidey(world))
            player.moverel(player.collidex(world),0)
            
            if player.steam < (player.steammax + 10 * player.items[1] - 1):
                player.steam += 1 + 0.05 * player.items[2] + 30 * player.items[3]
                player.items[3] = 0
            if player.rect.center[1] < -20 or player.rect.center[1] > 500:
                player.health -= 1
    
            
            #Scrollin' on the river...
            if player.rect.right > 420:
                distance =  round(420 - player.rect.right,0)
                for i in range(len(world)):
                    for j in range(len(world[i])):
                        world[i][j].moverel(distance * i / 16,0)
                for steambot in steamlist:
                    steambot.moverel(distance,0)
                player.moverel(distance,0)
    
            if player.rect.left <= 300:
                distance = round(300 - player.rect.left ,0)
                for i in range(len(world)):
                    for j in range(len(world[i])):
                         world[i][j].moverel(distance * i / 16,0)
                
                for steambot in steamlist:
                    steambot.moverel(distance,0)
                player.moverel(distance,0)
            
            player.draw(screen)
            for i in range(len(world)):
                if i > 16:
                    for j in range(len(world[i])):
                        world[i][j].draw(screen)
            if downlist.count(K_u):
                pygame.image.save(screen, time.strftime("%S.bmp") )
              #  delayb = 0
                    #Heads up display
            hud[0].pointlist[1][1]  = player.steam
            hud[0].pointlist[2][1]  = player.steam
            hud[1].pointlist[1][1]  = (player.steammax + 10 * player.items[1])
            hud[1].pointlist[2][1]  = (player.steammax + 10 * player.items[1])
            hud[2].pointlist[1][1]  = player.health
            hud[2].pointlist[2][1]  = player.health
            hud[3].pointlist[1][1]  = 100
            hud[3].pointlist[2][1]  = 100
            for each in hud:  
                each.draw(screen)
            
            pygame.display.flip()

    
    
    

if __name__ == '__main__': main()

