
#VB
import pygame,os
from pygame.locals import *
from random import choice
from funciones import *

def block(pos,bloques):
    mx,my=pos
    for b in bloques:
        for x,y in bloques[b]:
            if x<=mx<=x+32 and y<=my<=y+32:
                return b
def init_sprite32(spritesList,spritesheet,sprtx,sprty,altura):
    for zz in range(30):
        spritesList.append(spritesheet.subsurface((sprtx*(zz),altura,sprtx,sprty)))
    for nbr in range(len(spritesList)):
        spritesList[nbr].set_colorkey((255,255,255)) # blanco = alpha
        spritesList[nbr] = spritesList[nbr].convert_alpha()
    return None

pygame.init()
font=pygame.font.SysFont("monospace",20)
fontof=pygame.font.SysFont("monospace",30)
os.environ['SDL_VIDEO_CENTERED'] = '1'
pygame.display.set_caption("MaPyrio")
#Variables de juego
pantalla    =  pygame.display.set_mode((256*2,240*2))
clock       =  pygame.time.Clock()
FPS         =  30
gameloop    =  True
jugador     =  {"posicion":(0,0),"vidas":5,"cayendo":False,"salto":0,"direc":"D","mov":0,"monedas":0,"fin":0,"accelv":0}
posvar      =  0
avance      =  False
vel         =  10
vvel        =  0
splash      =  1
pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=4096)
nomonedas   =  []
loop        =  pygame.mixer.Sound("sound/loopcut.ogg")
coin        =  pygame.mixer.Sound("sound/coin.ogg")
pop        =  pygame.mixer.Sound("sound/pop.ogg")
win        =  pygame.mixer.Sound("sound/win.ogg")
splashScreen=  pygame.image.load(os.path.join("recursos","mapirio_splash.png")).convert_alpha()
startScreen =  pygame.image.load(os.path.join("recursos","fondo1.jpg")).convert()
bloques     =  pygame.image.load(os.path.join("recursos","bloquesx2b.png")).convert_alpha()
Mapy        =  [pygame.image.load(os.path.join("recursos","mapy_static.png")).convert_alpha(),
    pygame.transform.flip(pygame.image.load(os.path.join("recursos","mapy_static.png")).convert_alpha(),True,False),
    pygame.image.load(os.path.join("recursos","mapy1.png")).convert_alpha(), 
    pygame.image.load(os.path.join("recursos","mapy2.png")).convert_alpha(),
    pygame.transform.flip(pygame.image.load(os.path.join("recursos","mapy1.png")).convert_alpha(),True,False),
    pygame.transform.flip(pygame.image.load(os.path.join("recursos","mapy2.png")).convert_alpha(),True,False),
    pygame.image.load(os.path.join("recursos","mapy_jump.png")).convert_alpha(),
    pygame.transform.flip(pygame.image.load(os.path.join("recursos","mapy_jump.png")).convert_alpha(),True,False)]

bloquesList =  list()
for i in range(27):
    init_sprite32(bloquesList,bloques,32,32,i*32)
bloquesDict={
        "T":pygame.image.load(os.path.join("recursos","tubo1.png")).convert_alpha(),
        "U":pygame.image.load(os.path.join("recursos","tubo2.png")).convert_alpha(),
        "B":pygame.image.load(os.path.join("recursos","tubo3.png")).convert_alpha(),
        "O":pygame.image.load(os.path.join("recursos","tubo4.png")).convert_alpha(),
        "n":pygame.image.load(os.path.join("recursos","nube1.png")).convert_alpha(),
        "u":pygame.image.load(os.path.join("recursos","nube2.png")).convert_alpha(),
        "b":pygame.image.load(os.path.join("recursos","nube3.png")).convert_alpha(),
        "X":pygame.image.load(os.path.join("recursos","block.png")).convert(),
        "x":pygame.image.load(os.path.join("recursos","pasto.png")).convert(),
        "?":bloquesList[0*30+24*1],
        "F":bloquesList[12*30+16*1],
        "f":bloquesList[13*30+16*1],
        "C":pygame.image.load(os.path.join("recursos","money3.png")).convert_alpha(),
        "M":pygame.image.load(os.path.join("recursos","enemy.png")).convert_alpha()
        }

loop.play(20)
Juego=True
while Juego:
    while splash:
        pygame.display.set_caption("Mapyrio | FPS: "+str(round(clock.get_fps(),2)))
        pantalla.blit(startScreen,(0,0))
        pantalla.blit(splashScreen,(0,120))
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()
            if event.type==pygame.KEYDOWN:
                if event.key == pygame.K_RETURN:
                    splash=0
                    gameloop=True
                    posvar=0
                    jugador     =  {"posicion":(0,0),"vidas":5,"cayendo":False,"salto":0,"direc":"D","mov":0,"monedas":0,"fin":0,"accelv":0}
                if event.key == pygame.K_ESCAPE:
                    exit()
            pygame.display.flip()


    M = open(os.path.join("Mundos","mundo1.mpr"),"r")
    mundo=[x.strip() for x in M ]
    charact=Mapy[1]

    x=0-posvar
    y=0
    if len(nomonedas)!=0:
        for elem in nomonedas:
            elem=[elem[0]-posvar,elem[1]]

    #COLOCACION DE BLOQUES
    bloquespos={x:set() for x in bloquesDict.keys()}
    for fila in mundo: 
                for tile in fila:
                        if tile=="A":
                                x+=32
                        else:
                                bloquespos[tile].add((x,y))
                                x+=32
                x=0-posvar
                y+=32

    posorig=dict(bloquespos)

    while gameloop:
        pygame.display.set_caption("Mapyrio | FPS: "+str(round(clock.get_fps(),2)))
        milliseconds = clock.tick(FPS)
        pantalla.blit(startScreen,(0-posvar*0.2,0))
        pantalla.blit(startScreen,(1024-posvar*0.2,0))
        pantalla.blit(startScreen,(2048-posvar*0.2,0))
        mouspos = pygame.mouse.get_pos()
        bloquespos={x:set() for x in bloquesDict.keys()}
        for tipo in posorig:
            for cx,cy in posorig[tipo]:
                pantalla.blit(bloquesDict[tipo],(cx-posvar,cy))
                bloquespos[tipo].add((cx-posvar,cy))


        mort=consultamuerte(jugador,bloquespos)
        if mort:
            pop.play()
            posvar=0

            if jugador["vidas"]==0:
                splash=1
                gameloop=0
            pass
        #MANEJO DE EVENTOS
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()
            if event.type==pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    jugador["direc"]="L"
                    jugador["mov"]=1     
                if event.key == pygame.K_RIGHT:
                    jugador["direc"]="R"
                    jugador["mov"]=1
                if event.key == pygame.K_UP and detectar_contacto(jugador["posicion"],bloquespos)["S"]  in "nubAC" :
                    saltar(jugador)

            if event.type==pygame.KEYUP:
                if event.key == pygame.K_LEFT:
                    jugador["direc"]="S"
                    jugador["mov"]=0
                if event.key == pygame.K_RIGHT:
                    jugador["direc"]="S"
                    jugador["mov"]=0
        mover_jugador(jugador,vel,vvel,avance,bloquespos)
        moment=pygame.time.get_ticks()
        #JUEGO!
        #print jugador["salto"],jugador["cayendo"]
        detectar_caida(jugador,bloquespos)
        if jugador["cayendo"]:
            jugador["accelv"]-=1
        else:
            if jugador["accelv"]>0:
                pass
            else:
                jugador["accelv"]=0
            #elif jugador["accelv"]<1.34: #Rebote - elif -> else:vaccel=0 //sin rebote
            #    jugador["accelv"]=0
            #else:
            #    jugador["accelv"]=jugador["accelv"]*-0.5

        #Switcheo de Sprite
        if jugador["direc"]=="L":
            if jugador["mov"]:
                if (moment/100)%2==0:
                    charact=Mapy[2]
                else:
                    charact=Mapy[3]
            elif jugador["cayendo"]:
                charact=Mapy[6]
            else:
                charact=Mapy[0]
        else:
            
            if jugador["mov"]:
                if (moment/100)%2==0:
                    charact=Mapy[4]
                else:
                    charact=Mapy[5]
            elif jugador["cayendo"]:
                charact=Mapy[7]
            else:
                charact=Mapy[1]
        pantalla.blit(charact,jugador["posicion"])
        if recogermonedas(jugador,bloquespos,posorig,posvar):
            coin.play()

        if jugador["posicion"][0]>=256 and jugador["direc"]!="S" and detectar_contacto(jugador["posicion"],bloquespos)["LD"] in "nubAC":
            posvar+=vel
            avance=True
        else: 
            avance=False
        
        C= detectar_contacto(jugador["posicion"],bloquespos)
        if "f" in C.values() or "F" in C.values():
            win.play()
            gameloop=0
            splash=True
        #posc=font.render("("+str(mouspos[0])+", "+str(mouspos[1])+")",1,(0,0,0))
        vidas=fontof.render("VIDAS: "+str(jugador["vidas"]),1,(255,255,255))
        moned=fontof.render("MONEDAS: "+str(jugador["monedas"]),1,(255,255,255))
        #posb=font.render(block(mouspos,bloquespos),1,(0,0,0))
        #pantalla.blit(posc,mouspos)
        #pantalla.blit(posb,(mouspos[0],mouspos[1]+15))
        pantalla.blit(vidas,(300,0))
        pantalla.blit(moned,(300,25))
        pygame.display.flip()
