#!/bin/python3
import pygame as pg
import sys,time,random,os,math,gtxt,maps,chara,obj
from itms import *
version = "Ver.ϵ-3"
#game windows setup
pg.mixer.pre_init(44100, -16, 1, 512)
pg.init()
size = width, height = 960,720
screen = pg.display.set_mode(size)
pg.display.set_caption("Sponge")
#font
font0 = pg.font.SysFont("monospace", 15)
font1 = pg.font.SysFont("monospace", 20)
font2 = pg.font.SysFont("Arial Black", 17)
font5 = pg.font.SysFont("Arial Black", 14)
font8 = pg.font.SysFont("Arial Black", 20)
font3 = pg.font.SysFont("impact", 30)
font4 = pg.font.Font("FSEX300.ttf",30)
font6 = pg.font.Font("FSEX300.ttf",22)
#control set
keydict1 = {"pg.K_UP" : "UP","pg.K_DOWN" : "DOWN", "pg.K_LEFT" : "LEFT", "pg.K_RIGHT" : "RIGHT",
            "pg.K_RETURN" : "A", "pg.K_z" : "A","pg.K_SPACE" : "A", "pg.K_ESCAPE" : "B",
            "pg.K_x" : "B", "pg.K_KP0" : "B", "pg.K_KP1" : "X", "pg.K_c": "X", "pg.K_LSHIFT" : "Y", "pg.K_RSHIFT" : "Y"}
keydict2 = {"pg.K_w" : "UP","pg.K_s" : "DOWN", "pg.K_a" : "LEFT", "pg.K_d" : "RIGHT",
            "pg.K_SPACE" : "A", "pg.K_q" : "B", "pg.K_e" : "X", "pg.K_i": "X", "pg.K_LSHIFT" : "Y", "pg.K_RSHIFT" : "Y"}
#player settings
player = {"tsst":0,"EVNTS": [], "pos" : [500,300],"maap" : "home", "moneyz" : 0, "inventory" : [], "lp" : "DOWN", "lap" : [500,300], "music" : pg.mixer.music.load('./music/3-_Title_song.mp3'), "inter":{},
          "nicholas" : {"name" : "ULO", "ATK" : 1, "DEF" : 0, "HP" : [10,10] ,"MANA" : [2,2] ,"SPD" :4 ,"XP" : 2,"LV" : 0,"equipped" : []},
          "char#2" : {"name" : None, "ATK" : None, "DEF" : None, "HP" : [None,None] ,"MANA" : [None,None] ,"SPD" :None ,"XP" : None,"LV" : None,"equipped" : [],},
          "charlist":["nicholas"]
          }
#default settings
try:
    sety = open ("./saves/settings", "r")
    settings = eval(sety.read())
    settings["text"] = eval(settings["text"]) 
    sety.close()
except:
    settings = {"txtspeed": 40 , "tbanispd": 0.5, "music": .75 , "sfx": 1 , "autorun": False, "Fullscreen": False,
                    "keydict": keydict1 ,"text": gtxt.en , "WALK" : 0 }
#color 
LBL = (100,255,255)
GRBL = (200,215,255)
WHT = (255,255,255)
WHT2 = (210,197,233)
LGNBL = (100,180,195)
IDK = (50,120,130)
BLK = (0,0,0)
DKGNBL = (25,45,49)
DKBL = (0,0,26)
PRPL = (98,76,121)
GREY = (50,40,60)
#clock initiation
clock = pg.time.Clock()
#sounddesigin
pg.mixer.set_num_channels(10)
sfx = { 'cont' : pg.mixer.Sound("./sound/Title_NG-Cont.wav"),
        'sett' : pg.mixer.Sound("./sound/Title_Cont-Sett.wav"),
        'exit' : pg.mixer.Sound("./sound/Title_Sett-Quit.wav"),
        'NG'   : pg.mixer.Sound("./sound/Title_Quit-NG.wav"),
        'ok'   : pg.mixer.Sound("./sound/Title_selection.wav")}
#music initiation
pg.mixer.music.set_volume(settings["music"])
def setsfx(v):
    global sfx
    for i in sfx.keys():
        sfx[i].set_volume(v)
setsfx(settings['sfx'])
#npc number
nbnpc = 0
#render initiation
obon = [[],[],[],[],[],[]] #objhb,oblit.objib.npchb.nplit.npcib
#text size definition
def size_minus_syntax(str,font):
    tmp = 0
    skip = 0
    tmp = 0
    aaa = 0
    for x in str:
        if x == "\b":
            if aaa == 0:
                skip = -0.5
                aaa = 1
            elif aaa == 2:
                skip = -1
                aaa = 0
            elif aaa == 1:
                skip = -1
                aaa = 2
        if x not in ["\b","零"] and skip == 0:
            tmp += font.size(x)[0]
        elif x != "零":
            skip +=1
    return tmp
#line return
def returnL(txt,pos,font,prnt=False,color=WHT,aali=False,surface=screen,format=0): #skip lines->dict{L1:Pos1...}
    yup = [""]
    skip = 0
    ret = {}
    col = color
    state = True
    yup = txt.split("\n") #line skip
    if format != 0:
        for i in range(len(yup)):
            while True:
                if size_minus_syntax(yup[i],font) <= format:
                    break
                elif size_minus_syntax(yup[i].split(" ")[-1],font) <= format:
                    try:
                        yup[i+1] = yup[i].split(" ")[-1]+" "+yup[i+1]
                    except IndexError:
                        yup.append("")
                        yup[i+1] = yup[i].split(" ")[-1]+" "+yup[i+1]
                    yup[i] = " ".join(yup[i].split(" ")[0:-1])
                else:
                    for j in range(len(yup[i])):
                        if size_minus_syntax(yup[i][0:j],font) <= format:
                            continue
                        else :
                            try :
                                yup[i+1] = yup[i][j-1:-1]+" "+yup[i+1]
                            except IndexError:
                                yup.append("")
                                yup[i+1] = yup[i][j-1:-1]+" "+yup[i+1]
                            yup[i] = yup[i][0:j-1]
                            break
    for j in range(len(yup)):
        while True:
            if yup[j] not in ret.keys():
                ret[yup[j]]=(pos[0],pos[1]+(j*(font.size(yup[j])[1])))
                break
            yup[j] += "零" 
    if prnt:
        for i in ret:
            skip = 0
            tmp = 0
            aaa = 0
            f = ""
            for x in i: # emphasis system (could use .split )
                if x == "\b":
                    state = False
                    if aaa == 0:
                        skip = -0.5
                        aaa = 1
                    elif aaa == 2:
                        col = color
                        f = ""
                        skip = -1
                        aaa = 0
                    elif aaa == 1:
                        skip = -1
                        col = eval(f)
                        aaa = 2
                if skip > 0 :
                    f+=x
                if x not in ["\b","零"] and skip == 0 :
                    state = True
                    surface.blit(font.render(x,aali,col),(ret[i][0]+tmp,ret[i][1]))
                    tmp += font.size(x)[0]
                elif x != "零":
                    skip +=1
    return [ret,state]

#maintain touch
def key(held=False , keydict = settings["keydict"] , mult = False):  #gets key inputs and return assigned function (see dict l.11)(A.B,X,Y,UP...)(the "held" if for testing if key is being held vs if key is being pressed
    ret = []
    if pg.event.get(pg.QUIT) != []:
        pg.quit()
        quit()
    if not held:
        for i in pg.event.get():    
            pressed = pg.key.get_pressed()
            for j in keydict:
                if pressed[eval(j)]:
                    if mult:
                        ret.append(keydict[j])
                    else:
                        return keydict[j]
    if held:
        pressed = pg.key.get_pressed()
        for j in keydict:
            if pressed[eval(j)]:
                if mult :
                    ret.append(keydict[j])
                else:    
                    return keydict[j]
    if mult:
        return ret

#texbox drawing
def textbox(txt,pos=((width/2-400,height-250),(800,150)),animation=True,colors=(WHT,BLK,PRPL),borderW=10,fontx=font4,surface=screen,aali=False,c = False): #txt syntax is a list with one txtbox per object str for normal text and lists for choices first color is text & edges second bg and third selected choice
    ret = []
    if animation and settings["tbanispd"] != 0: #animation
        for i in range(30):
            if key() in ["A","B"]:                                                                                           
                break
            clock.tick_busy_loop(30/settings["tbanispd"])
            pg.draw.rect( surface ,colors[1],(pos[0][0],pos[0][1]+pos[1][1]/2-math.log(i+2,2)*(pos[1][1]/10),pos[1][0],math.log(i+2,2)*(pos[1][1]/5)))
            pg.draw.rect( surface ,colors[0],(pos[0][0],pos[0][1]+pos[1][1]/2-math.log(i+2,2)*(pos[1][1]/10),pos[1][0],math.log(i+2,2)*(pos[1][1]/5)),borderW)
            pg.display.flip()
    for j in range(len(txt)):
        pg.display.flip()
        if type(txt[j]) is str: 
            state = True
            for i in range(len(txt[j])):  #outputs text using return line function to print
                pg.draw.rect( surface ,colors[1],(pos[0][0],pos[0][1],pos[1][0],pos[1][1]))
                pg.draw.rect( surface ,colors[0],(pos[0][0],pos[0][1],pos[1][0],pos[1][1]),borderW)
                state = returnL(txt[j][0:i+1],(pos[0][0]+20,pos[0][1]+10),fontx,True,colors[0],aali,surface,pos[1][0]-40)[1]
                if key(True) == "A" and state: #speeds text when pressing A
                    clock.tick_busy_loop(4*settings["txtspeed"])
                elif state:
                    clock.tick_busy_loop(settings["txtspeed"])
                pg.display.flip()
            while True:
                if key() == "A" or c :
                    break
        else:
            np = [pos[0][0]+20,pos[0][1]+10] #temp variable to store new position to print each choice
            tmp = {}
            for k in txt[j]:
                state = True
                for i in range(len(k)):  #outputs text using return line function to print
                    pg.draw.rect( surface ,colors[1],(pos[0][0],np[1],pos[1][0],pos[0][1]+pos[1][1]-np[1]))
                    pg.draw.rect( surface ,colors[0],(pos[0][0],pos[0][1],pos[1][0],pos[1][1]),borderW)
                    tmpp = returnL(k[0:i+1],np,fontx,True,colors[0],aali,surface,pos[1][0]-40)
                    state,tmp[k] = tmpp[1],tmpp[0]
                    if key(True) == "A" and state: #speeds text when pressing A
                        clock.tick_busy_loop(3*settings["txtspeed"])
                    elif state:
                        clock.tick_busy_loop(settings["txtspeed"])
                    pg.display.flip()
                np[1] = list(list(tmp.values())[-1].values())[0][1]+fontx.size(list(tmp.keys())[-1])[1] #updates new position
            cltmp = [colors[2]] #list of colors
            ch = 0 #pointer to assign choice to color
            for l in range(len(txt[j])-1):
                cltmp.append(colors[0])
            while True:
                for l in range(len(txt[j])): #print choices with new colors
                    returnL(txt[j][l],list(list(tmp.values())[l].values())[0],fontx,True,cltmp[(l+ch)%len(txt[j])],aali,surface,pos[1][0]-40)
                pg.display.flip()
                inpt = key()
                if inpt in ["UP","LEFT"]: #below cursor mouvements
                    ch += 1
                if inpt in ["DOWN","RIGHT"]:
                    ch -= 1
                if inpt == "A":
                    ret.append("ch"+str(ch%len(txt[j]))) #returns "chX" w/ X being the selected choice (includes 0)
                    break
    return ret
def music(nm,fadein = False):
    if nm!=player["music"]:
        player["music"] = nm
        pg.mixer.music.stop()
        pg.mixer.music.load(nm)
        pg.mixer.music.play(-1)
    if fadein:
        pg.mixer.music.fadein(1000)
    pg.mixer.music.set_volume(settings["music"])
#new game
def NG(): #lauches intro and starts prologue
    music("./music/NG.mp3") 
    screen.fill(BLK)
    box = ((width/2-400,height/2-105),(800,210))
    clrs = (LGNBL,IDK,LBL)
    textbox(settings["text"].intro.txt,box,True,clrs)
    while True:
        ch = textbox(settings["text"].intro.chx,box,False,clrs)
        if ch[0] == "ch2":
            pg.mixer.music.set_volume(0)
            textbox(settings["text"].intro.ch2,box,False,clrs)
            pg.quit()
            quit()
        if ch[0] == "ch1":
            txt = ["eh"]
            textbox(settings["text"].intro.ch1,box,False,clrs)
        if ch[0] == "ch0":
            textbox(settings["text"].intro.ch0,box,False,clrs)
            for opacity in range(0,255, 5):
                if opacity == 0 :
                    pg.mixer.music.fadeout(51*60)
                img = pg.Surface(size)
                img.set_alpha(opacity)
                img.fill(BLK)
                screen.blit(img,(0,0)) 
                pg.display.flip() 
                pg.time.delay(60)
            return
#loading menu
def SaveM(sv=True):
    cursor =  [(WHT,BLK),(GREY,BLK),(GREY,BLK),(GREY,BLK)]
    cursor2 = 0
    timothe = 0
    if sv:
        screen.blit(font5.render("Save",True,WHT),(width/2-390,30))
    else:
        screen.blit(font5.render("Load",True,WHT),(width/2-390,30))
    pg.draw.rect(screen ,BLK,(width/2-400,50,800,100))
    pg.draw.rect(screen ,WHT,(width/2-400,50,800,100),10)
    while True:                                                   
        clock.tick_busy_loop(120)
        timothe = (timothe+1)%120
        slot = ["slot 1","slot 2","autosave"]
        if cursor2 != 3:
            try:
                if cursor2 == 2:
                    savea = open("./saves/auto",'r')
                else:
                    savea = open("./saves/save"+str(cursor2+1),'r')
                tmp = eval(savea.read())
                if int(timothe/60) == 0:
                    slot[cursor2] = "lv."+str(tmp["nicholas"]["LV"])+" "+tmp["maap"]
                savea.close()
                overr = True
            except:
                overr = False
        pg.draw.rect( screen ,cursor[3][1],(width/2+225,150-25,150,-50))
        pg.draw.rect( screen ,cursor[3][0],(width/2+225,150-25,150,-50), 5 )
        screen.blit(font5.render("BACK",True,cursor[3][0]),(width/2+225+75-font5.size("BACK")[0]/2,150-25-25-font5.size("BACK")[1]/2))
        pg.draw.rect( screen ,cursor[2][1],(width/2+25,150-25,150,-50))
        pg.draw.rect( screen ,cursor[2][0],(width/2+25,150-25,150,-50), 5 )
        screen.blit(font5.render(slot[2],True,cursor[2][0]),(width/2+25+75-font5.size(slot[2])[0]/2,150-25-25-font5.size(slot[2])[1]/2))
        pg.draw.rect( screen ,cursor[1][1],(width/2-175,150-25,150,-50))
        pg.draw.rect( screen ,cursor[1][0],(width/2-175,150-25,150,-50), 5 )
        screen.blit(font5.render(slot[1],True,cursor[1][0]),(width/2-175+75-font5.size(slot[1])[0]/2,150-25-25-font5.size(slot[1])[1]/2))
        pg.draw.rect( screen ,cursor[0][1],(width/2-375,150-25,150,-50))
        pg.draw.rect( screen ,cursor[0][0],(width/2-375,150-25,150,-50), 5 )
        screen.blit(font5.render(slot[0],True,cursor[0][0]),(width/2-375+75-font5.size(slot[0])[0]/2,150-25-25-font5.size(slot[0])[1]/2))
        pg.display.flip()
        inpt = key()
        if inpt in ["UP","LEFT"] : #below cursor mouvements
            cursor[0],cursor[1],cursor[2],cursor[3] = cursor[1],cursor[2],cursor[3],cursor[0]
            cursor2 -= 1
            timothe = 0
        if inpt in ["DOWN","RIGHT"]:
            cursor[0],cursor[1],cursor[2],cursor[3] = cursor[3],cursor[0],cursor[1],cursor[2]
            cursor2 += 1
            timothe = 0
        cursor2 = cursor2%4
        if inpt == "A":
            if cursor2 == 3:
                return False
            if sv:
                if overr:
                   textbox(["Do you want to\noverride this save ?"],((width/2-400,50),(800,100)),False,c=True)
                   ch = textbox([["Yes","No"]],((width/2+100,60),(100,80)),True,(WHT,BLK,GREY),5)
                   pg.draw.rect(screen ,BLK,(width/2-400,50,800,100))
                   pg.draw.rect(screen ,WHT,(width/2-400,50,800,100),10)
                   if ch[0] == 'ch1' :  
                       continue
                if cursor2 == 2:
                    save()
                if cursor2 == 1:
                    save("save2")
                if cursor2 == 0:
                    save("save1")
                cursor = [(GREY,BLK),(GREY,BLK),(GREY,BLK),(WHT,BLK)]
                cursor2 = 3
            else:
                if not overr:
                    textbox(["This save slot is empty"],((width/2-400,50),(800,100)),False,)
                    pg.draw.rect(screen ,BLK,(width/2-400,50,800,100))     
                    pg.draw.rect(screen ,WHT,(width/2-400,50,800,100),10)
                    continue
                if cursor2 == 2:
                    load()
                if cursor2 == 1:
                    load("save2")
                if cursor2 == 0:
                    load("save1")
                return True

#loading
def load(slot="auto"):
    global player
    global nbnpc
    save = open("./saves/"+slot,'r')
    p = eval(save.read())
    nbnpc = p.pop("nbnpc")
    music(p["music"])
    player = p 
    save.close
#save
def save(slot="auto"):
    global player
    try:
        save = open("./saves/"+slot,'w')
    except:
        x = open("./saves/"+slot,'x')
        x.close
        save = open("./saves/"+slot,'w')
    player["nbnpc"]=nbnpc
    save.write(str(player))
    del player["nbnpc"]
    save.close


def ST(stv):#settings (to save automatically)
    global settings
    findobject = pg.mixer.Sound("./music/Itemfound.wav")
    pat = False
    if stv:
        screen.fill(DKBL)
    else:
        img = pg.Surface(size)
        img.set_alpha(128)
        img.fill(BLK)
        screen.blit(img,(0,0))
    cursor = [(WHT,BLK),(GREY,BLK),(GREY,BLK)]
    x = [[ (settings["txtspeed"]-10)*30/9+width/2-100, width/2+(1-settings["tbanispd"])*300-100],[width/2+settings["music"]*300-100,width/2+settings["sfx"]*300-100],settings["text"]]
    while True :
        cursor2 = [(WHT,BLK,PRPL),(GREY,BLK,GREY)]
        inpt = key()
        pg.draw.rect( screen ,BLK ,(width/2-325,height-375,650,-200))
        pg.draw.rect( screen ,WHT ,(width/2-325,height-375,650,-200), 5 )
        pg.draw.rect( screen ,BLK ,(width/2-275,height-625,550,-100))
        pg.draw.rect( screen ,WHT ,(width/2-275,height-625,550,-100),5)
        pg.draw.rect( screen ,cursor[0][1],(width/2-250,height-600,150,-50))
        pg.draw.rect( screen ,cursor[0][0],(width/2-250,height-600,150,-50), 5 )
        screen.blit(font2.render("TEXTBOX",True,cursor[0][0]),(width/2-250+75-font2.size("TEXTBOX")[0]/2,height-600-25-font2.size("TEXTBOX")[1]/2))
        pg.draw.rect( screen ,cursor[1][1],(width/2-75,height-600,150,-50))
        pg.draw.rect( screen ,cursor[1][0],(width/2-75,height-600,150,-50), 5 )
        screen.blit(font2.render("SOUND",True,cursor[1][0]),(width/2-font2.size("SOUND")[0]/2,height-600-25-font2.size("SOUND")[1]/2))
        pg.draw.rect( screen ,cursor[2][1],(width/2+100,height-600,150,-50))
        pg.draw.rect( screen ,cursor[2][0],(width/2+100,height-600,150,-50), 5 )
        screen.blit(font2.render("LANGUAGE",True,cursor[2][0]),(width/2+100+75-font2.size("LANGUAGE")[0]/2,height-600-25-font2.size("LANGUAGE")[1]/2))
        if inpt in ["UP","LEFT"] : #below cursor mouvements
            cursor[0],cursor[1],cursor[2], = cursor[1],cursor[2],cursor[0]
        if inpt in ["DOWN","RIGHT"]:
            cursor[0],cursor[1],cursor[2] = cursor[2],cursor[0],cursor[1]
        if inpt == "B":
            try:
                seti = open("./saves/settings",'w')
            except:
                x = open("./saves/settings",'x')
                x.close
                seti= open("./saves/settings",'w')
            settings["text"] = str(settings["text"])[8:-2] 
            seti.write(str(settings)) 
            settings["text"] = eval(settings["text"]) 
            seti.close
            break
        if cursor[0][0] == WHT:
            pg.draw.rect( screen ,BLK,(width/2-300,height-500,150,-50))
            pg.draw.rect( screen ,GREY,(width/2-300,height-500,150,-50), 5 )
            pg.draw.rect( screen ,GREY,(width/2-100,height-510,320,-30))
            pg.draw.rect( screen ,GREY,(x[0][0],height-510,20,-30))
            screen.blit(font2.render("TEXTSPEED",True,GREY),(width/2-300+75-font2.size("TEXTSPEED")[0]/2,height-500-25-font2.size("TEXTSPEED")[1]/2))
            pg.draw.rect( screen ,BLK,(width/2-300,height-425,150,-50))
            pg.draw.rect( screen ,GREY,(width/2-300,height-425,150,-50), 5 )
            pg.draw.rect( screen ,GREY,(width/2-100,height-435,320,-30))
            pg.draw.rect( screen ,GREY,(x[0][1],height-435,20,-30))
            screen.blit(font2.render("TBANISPD",True,GREY),(width/2-300+75-font2.size("TBANISPD")[0]/2,height-425-25-font2.size("TBANISPD")[1]/2))
            pg.display.flip()
        if cursor[1][0] == WHT:
            pg.draw.rect( screen ,BLK,(width/2-300,height-500,150,-50))
            pg.draw.rect( screen ,GREY,(width/2-300,height-500,150,-50), 5 )
            pg.draw.rect( screen ,GREY,(width/2-100,height-510,320,-30))
            pg.draw.rect( screen ,GREY,(x[1][0],height-510,20,-30))
            screen.blit(font2.render("MUSIC",True,GREY),(width/2-300+75-font2.size("MUSIC")[0]/2,height-500-25-font2.size("MUSIC")[1]/2))
            pg.draw.rect( screen ,BLK,(width/2-300,height-425,150,-50))
            pg.draw.rect( screen ,GREY,(width/2-300,height-425,150,-50), 5 )
            pg.draw.rect( screen ,GREY,(width/2-100,height-435,320,-30))
            pg.draw.rect( screen ,GREY,(x[1][1],height-435,20,-30))
            screen.blit(font2.render("SOUND",True,GREY),(width/2-300+75-font2.size("SOUND")[0]/2,height-425-25-font2.size("SOUND")[1]/2))
            pg.display.flip()
        if cursor[2][0] ==WHT:
            pg.draw.rect( screen ,BLK,(width/2-170,height-450,150,-50))
            pg.draw.rect( screen ,GREY,(width/2-170,height-450,150,-50),5)
            screen.blit(font2.render("ENGLISH",True,GREY),(width/2-170+75-font2.size("ENGLISH")[0]/2,height-450-25-font2.size("ENGLISH")[1]/2))
            pg.draw.rect( screen ,BLK,(width/2+20,height-450,150,-50))
            pg.draw.rect( screen ,GREY,(width/2+20,height-450,150,-50),5)
            screen.blit(font2.render("FRANçAIS",True,GREY),(width/2+20+75-font2.size("FRANçAIS")[0]/2,height-450-25-font2.size("FRANçAIS")[1]/2))
            pg.display.flip()
            
        if inpt == "A":
            if cursor[0][0]== WHT:
                while True:
                    clock.tick_busy_loop(120)
                    inpt = key()
                    pg.draw.rect( screen ,cursor2[0][1],(width/2-300,height-500,150,-50))
                    pg.draw.rect( screen ,cursor2[0][0],(width/2-300,height-500,150,-50), 5 )
                    pg.draw.rect( screen ,cursor2[0][0],(width/2-100,height-510,320,-30))
                    pg.draw.rect( screen ,cursor2[0][2],(x[0][0],height-510,20,-30))
                    screen.blit(font2.render("TEXTSPEED",True,cursor2[0][0]),(width/2-300+75-font2.size("TEXTSPEED")[0]/2,height-500-25-font2.size("TEXTSPEED")[1]/2))
                    pg.draw.rect( screen ,cursor2[1][1],(width/2-300,height-425,150,-50))
                    pg.draw.rect( screen ,cursor2[1][0],(width/2-300,height-425,150,-50), 5 )
                    pg.draw.rect( screen ,cursor2[1][0],(width/2-100,height-435,320,-30))
                    pg.draw.rect( screen ,cursor2[1][2],(x[0][1],height-435,20,-30))
                    screen.blit(font2.render("TBANISPD",True,cursor2[1][0]),(width/2-300+75-font2.size("TBANISPD")[0]/2,height-425-25-font2.size("TBANISPD")[1]/2))
                    pg.display.flip()
                    if inpt in ["UP","DOWN"]:
                        cursor2[1],cursor2[0] = cursor2[0],cursor2[1]
                    if cursor2[0] == (WHT,BLK,PRPL):
                        if key(True) == "LEFT" and x[0][0]>width/2-100:
                            x[0][0] -= 1
                        if key(True) == "RIGHT" and x[0][0]<width/2 + 200:
                            x[0][0] += 1
                        settings["txtspeed"] = (x[0][0] - width/2 +100)*(90/300) + 10
                    else:
                        if key(True) == "LEFT" and x[0][1]>width/2-100 :
                            x[0][1] -= 40/40
                        if key(True) == "RIGHT" and x[0][1]<width/2 + 200:
                            x[0][1] += 40/40
                        settings["tbanispd"] =1- (x[0][1] - width/2 +100)/300

                    if inpt == "B":
                        break
                        
            if cursor[1][0]== WHT:
                while True:
                    clock.tick_busy_loop(120)
                    inpt = key()
                    pg.draw.rect( screen ,cursor2[0][1],(width/2-300,height-500,150,-50))
                    pg.draw.rect( screen ,cursor2[0][0],(width/2-300,height-500,150,-50), 5 )
                    pg.draw.rect( screen ,cursor2[0][0],(width/2-100,height-510,320,-30))
                    pg.draw.rect( screen ,cursor2[0][2],(x[1][0],height-510,20,-30))
                    screen.blit(font2.render("MUSIC",True,cursor2[0][0]),(width/2-300+75-font2.size("MUSIC")[0]/2,height-500-25-font2.size("MUSIC")[1]/2))
                    pg.draw.rect( screen ,cursor2[1][1],(width/2-300,height-425,150,-50))
                    pg.draw.rect( screen ,cursor2[1][0],(width/2-300,height-425,150,-50), 5 )
                    pg.draw.rect( screen ,cursor2[1][0],(width/2-100,height-435,320,-30))
                    pg.draw.rect( screen ,cursor2[1][2],(x[1][1],height-435,20,-30))
                    screen.blit(font2.render("SOUND",True,cursor2[1][0]),(width/2-300+75-font2.size("SOUND")[0]/2,height-425-25-font2.size("SOUND")[1]/2))
                    pg.display.flip()
                    if inpt in ["UP","DOWN"]:
                        cursor2[0],cursor2[1] = cursor2[1],cursor2[0]
                    if cursor2[0] == (WHT,BLK,PRPL):
                        if key(True) == "LEFT" and x[1][0]>width/2-100:
                            x[1][0] -= 32/32
            
                        if key(True) == "RIGHT" and x[1][0]<width/2 + 200:
                            x[1][0] += 32/32
                        settings["music"] = (x[1][0] -width/2 +100)/300
                        pg.mixer.music.set_volume(settings["music"])
                       
                    else:
                        
                        if key(True) == "LEFT" and x[1][1]>width/2-100:
                            x[1][1] -= 32/32
                            pat = True
                        
                            
                        elif key(True) == "RIGHT" and x[1][1]<width/2 + 200:
                            x[1][1] += 32/32
                            pat = True

                        elif pat:
                            pat = False
                            settings["sfx"] = (x[1][1] -width/2 +100)/300
                            findobject.set_volume(settings["sfx"])
                            findobject.play()
                            setsfx(settings["sfx"])
                    if inpt == "B":
                        break
                                                
            if cursor[2][0]== WHT:
                while True:
                    inpt = key()
                    pg.draw.rect( screen ,cursor2[0][1],(width/2-170,height-450,150,-50))
                    pg.draw.rect( screen ,cursor2[0][0],(width/2-170,height-450,150,-50),5)
                    screen.blit(font2.render("ENGLISH",True,cursor2[0][0]),(width/2-170+75-font2.size("ENGLISH")[0]/2,height-450-25-font2.size("ENGLISH")[1]/2))
                    pg.draw.rect( screen ,cursor2[1][1],(width/2+20,height-450,150,-50))
                    pg.draw.rect( screen ,cursor2[1][0],(width/2+20,height-450,150,-50),5)
                    screen.blit(font2.render("FRANçAIS",True,cursor2[1][0]),(width/2+20+75-font2.size("FRANçAIS")[0]/2,height-450-25-font2.size("FRANçAIS")[1]/2))
                    pg.display.flip()
                    if inpt in ["UP","DOWN","LEFT","RIGHT"]:
                        cursor2[0],cursor2[1] = cursor2[1],cursor2[0]
                    if inpt == "B":
                        break
                    if inpt == "A":
                        if cursor2[0][0] == WHT:
                           settings["text"] = gtxt.en
                        else:
                            settings["text"] = gtxt.fr
        pg.display.flip()
def resblit(img,offset=(0,0),init=(960,720)):
    screen.blit(img,(offset[0]+width/2-init[0]/2,offset[1]+height/2-init[1]/2))
def MePr():#Title screen
    rmp = 0 
    while True: #pre-title-screen (most of it is the blinking)
        rmp +=1
        inpt = key()
        clock.tick_busy_loop(120)
        resblit(pg.image.load(os.path.join('TTSBG1.png')),(0,0))
        resblit(pg.image.load(os.path.join('FEX5.png')),(560,180))
        resblit(pg.image.load(os.path.join('Shadow.png')),(0,0))
        screen.blit(pg.image.load(os.path.join('TTL.png')),(width/2-300,height/2-220))
        if (rmp+30)%60 == 0: #modulo is the blinking speed (120 = once per second,90 = 1.5 times per second)
            pg.display.flip()
        screen.blit(font4.render("Press any key to continue",True,GREY),(width/2.25-font4.size("Press any key to continue")[0]/2,height/2+100))
        if rmp%60 == 0:
            pg.display.flip()
        if inpt != None:
            for i in range(3): #flashing animation upon confirming
                screen.blit(font4.render("Press any key to continue",True,GREY),(width/2.25-font4.size("Press any key to continue")[0]/2,height/2+100))
                clock.tick_busy_loop(7.5/(i+1))
                pg.display.flip()
                resblit(pg.image.load(os.path.join('TTSBG1.png')),(0,0))
                resblit(pg.image.load(os.path.join('FEX5.png')),(560,180))        
                resblit(pg.image.load(os.path.join('Shadow.png')),(0,0))
                screen.blit(pg.image.load(os.path.join('TTL.png')),(width/2-300,height/2-220))
                clock.tick_busy_loop(7.5/(i+1))
                pg.display.flip()
            break
    pg.mixer.music.play(-1)
    pg.mixer.music.set_volume(settings['music'])
    resblit(pg.image.load(os.path.join('TTSBG1.png')),(0,0))
    resblit(pg.image.load(os.path.join('TTL.png')),(50,50))
    pg.draw.rect( screen ,BLK,(width/2-400,height-50,800,-100))
    pg.draw.rect( screen ,PRPL,(width/2-400,height-50,800,-100),10)
    screen.blit(font1.render("©DAKAS Inc.",True,(240,200,255)),(width/2-font1.size("©DAKAS Inc.")[0]/2,height-35))
    screen.blit(font0.render(version,True,GREY),(width-font0.size(version)[0]-20,height-20))
    cursor =  [(WHT,DKBL),(PRPL,DKBL),(PRPL,DKBL),(PRPL,DKBL)] # P0 = ng P1 = continue P2 = settings P3 = QUIT
    cursor2 = [WHT,PRPL]
    FLKR = ["0","5"]
    LOFF = False#above is background,title,and textbox for menu
    skoop = False
    DURT = -1
    sfxch=0
    while True:#screen animation + cursor mouvements (returns funtion to execute upon confirm)
        clock.tick_busy_loop(120)     
        if LOFF or skoop:#timer for streetlight flicker
            DURT-=20
            if DURT < 0 or skoop:
                resblit(pg.image.load(os.path.join('FEX'+FLKR[0]+'.png')),(560,180))
                LOFF = False
        pg.draw.rect( screen ,cursor[3][1],(width/2+225,height-50-25,150,-50))
        pg.draw.rect( screen ,cursor[3][0],(width/2+225,height-50-25,150,-50), 5 )
        screen.blit(font2.render("EXIT",True,cursor[3][0]),(width/2+225+75-font2.size("EXIT")[0]/2,height-50-25-25-font2.size("EXIT")[1]/2))
        pg.draw.rect( screen ,cursor[2][1],(width/2+25,height-50-25,150,-50))
        pg.draw.rect( screen ,cursor[2][0],(width/2+25,height-50-25,150,-50), 5 )
        screen.blit(font2.render("SETTINGS",True,cursor[2][0]),(width/2+25+75-font2.size("SETTINGS")[0]/2,height-50-25-25-font2.size("SETTINGS")[1]/2))
        pg.draw.rect( screen ,cursor[1][1],(width/2-175,height-50-25,150,-50))
        pg.draw.rect( screen ,cursor[1][0],(width/2-175,height-50-25,150,-50), 5 )
        screen.blit(font2.render("CONTINUE",True,cursor[1][0]),(width/2-175+75-font2.size("CONTINUE")[0]/2,height-50-25-25-font2.size("CONTINUE")[1]/2))
        pg.draw.rect( screen ,cursor[0][1],(width/2-375,height-50-25,150,-50))
        pg.draw.rect( screen ,cursor[0][0],(width/2-375,height-50-25,150,-50), 5 )
        screen.blit(font2.render("NEW GAME",True,cursor[0][0]),(width/2-375+75-font2.size("NEW GAME")[0]/2,height-50-25-25-font2.size("NEW GAME")[1]/2))
        if random.random() > 0.995 and LOFF == False and not skoop: #street light flicker
            resblit(pg.image.load(os.path.join('FEX'+FLKR[1]+'.png')),(560,180))
            DURT = random.randint(0,100)
            LOFF=True
        pg.display.flip()
        if skoop:
            for i in range(6):#streetlight animation upon exit
                resblit(pg.image.load(os.path.join('FEX'+str(i)+'.png')),(560,180))
                clock.tick_busy_loop(6)
                pg.display.flip()
            pg.quit()
            quit()
        inpt = key()
        if inpt in ["UP","LEFT"] : #below cursor mouvements
            cursor[0],cursor[1],cursor[2],cursor[3] = cursor[1],cursor[2],cursor[3],cursor[0]
        if inpt in ["DOWN","RIGHT"]:
            cursor[0],cursor[1],cursor[2],cursor[3] = cursor[3],cursor[0],cursor[1],cursor[2]
        if inpt in ["DOWN","RIGHT","UP","LEFT"]:
            if cursor[0][0] == WHT:
                pg.mixer.Channel(sfxch).play(sfx['NG'])
            elif cursor[1][0] == WHT:
                pg.mixer.Channel(sfxch).play(sfx['cont'])
            elif cursor[2][0] == WHT:
                pg.mixer.Channel(sfxch).play(sfx['sett'])
            else:
                pg.mixer.Channel(sfxch).play(sfx['exit'])
            sfxch = (sfxch+1)%10
        elif inpt == "A": #check selection to confirm
            sfx['ok'].play()
            if cursor[0][0]==WHT:
                return "NG()"
            if cursor[1][0]==WHT:
                tmp = SaveM(False)
                if tmp:
                    return 'cnt = True'
                screen.fill(BLK)
                resblit(pg.image.load(os.path.join('TTSBG1.png')),(0,0))                    
                resblit(pg.image.load(os.path.join('TTL.png')),(50,50))
                pg.draw.rect( screen ,BLK,(width/2-400,height-50,800,-100))
                pg.draw.rect( screen ,PRPL,(width/2-400,height-50,800,-100),10)
            if cursor[2][0]==WHT:
                ST(True)
                screen.fill(BLK)
                resblit(pg.image.load(os.path.join('TTSBG1.png')),(0,0))                    
                resblit(pg.image.load(os.path.join('TTL.png')),(50,50))
                pg.draw.rect( screen ,BLK,(width/2-400,height-50,800,-100))
                pg.draw.rect( screen ,PRPL,(width/2-400,height-50,800,-100),10)

            if cursor[3][0]==WHT :
                textbox(["Are you sure ?"],((width/2-120,height/2-75),(240,200)),False,c=True)
                ch = textbox([["yes","no"]],((width/2-100,height/2+5),(200,100)),True,(PRPL,DKBL,WHT),5)
                resblit(pg.image.load(os.path.join('TTSBG1.png')),(0,0))
                resblit(pg.image.load(os.path.join('TTL.png')),(50,50))
                pg.draw.rect( screen ,BLK,(width/2-400,height-50,800,-100))
                pg.draw.rect( screen ,PRPL,(width/2-400,height-50,800,-100),10)
                if ch[0] == 'ch0' :
                    skoop = True
                    continue
#colision test and interaction
def coll(pos,lap,hb,maaaap=[],obj=[],): 
    if pos != lap : 
        for i in hb:
            for j in maaaap+obj:
                if i.colliderect(j) :
                    return True
    return False
#collision for player and npc
def coll1(pos,lap,hb,maaaap=[],obj=[]):
    global player              
    a = list(pos)
    if not coll(pos,lap,eval(hb),maaaap,obj) :
        return pos
    for pt in range(2):
        pos[pt] = lap[pt]
        pos[(pt+1)%2] = a[(pt+1)%2] 
        if not coll(pos,lap,eval(hb),maaaap,obj):
            return pos
    else:
        return lap
#movement
def mv(fra,timer):
    global player
    Aquoi = key(held=True, mult=True)
    br = False
    fr = fra 
    player["lap"] = [player["pos"][0],player["pos"][1]]
    RP = {"UP":"DOWN","LEFT":"RIGHT","DOWN":"UP","RIGHT":"LEFT"}
    for i in ["UP","LEFT","DOWN","RIGHT"]:
        if i in Aquoi and RP[i] in Aquoi:
            Aquoi.pop(Aquoi.index(RP[i]))
            Aquoi.pop(Aquoi.index(i))
    if settings["WALK"] == 1:
        tmp = [1,["UP","DOWN","LEFT","RIGHT"]]
    else:
        tmp = [0,["RIGHT","LEFT","DOWN","UP"]]
    for tp,uq in enumerate(tmp[1]):
        if uq in Aquoi:
            tpp = tmp[0]*(3-tp)+(1-tmp[0])*(tp)
            player["pos"][int(tpp/2)] += round(7*(((tpp+1)%2)*2-1)/(len(Aquoi)**.5))
            player["lp"] = uq
            br = True
    else:
        if not br:
            tim = 0
            fr = "P"
    if br:
        tim = (timer+1)%50
        if timer == 0:
            fr = 1
        elif timer == 25:
            fr = 2
    Aquoi.insert(0,player["lp"])
    return Aquoi[-1],fr,tim
#switching between maps
def mapsw(mpa,poss):
    global player
    global nbnpc
    global obon
    if "mblock" not in player["EVNTS"]:
        music(mpa.music)
    objhb = []
    oblit = []
    objib = []
    nbnpc = mpa.npc
    npchb = []
    nplit = []
    npcib = []
    for i in mpa.obj:
        for j in (eval("obj."+i[0])(i[1],i[2]).hb):
            objhb.append(j)
        for j in (eval("obj."+i[0])(i[1],i[2]).ib):
            objib.append(j)
        oblit.append([eval("obj."+i[0]).skn,i[1],i[2],i[3],i[4]])
    for i in mpa.ldz:
        objib.append(i)
    for h,i in enumerate(nbnpc):
        if i[0] not in player["inter"].keys():
            player["inter"][i[0]] = i[:-3]
        else :
            nbnpc[h] = player["inter"][i[0]]+[0,0,0]
        for j in (eval("chara.npc."+i[0][:-2])(i[1],i[2],(i[0],player["inter"][i[0]][5]),i[7]).hb):
            npchb.append([j,i[0]])
        for j in (eval("chara.npc."+i[0][:-2])(i[1],i[2],(i[0],player["inter"][i[0]][5]),i[7]).ib):
            npcib.append(j)
        nplit.append([eval("chara.npc."+i[0][:-2]).skn(),i[1],i[2],i[3],i[4]])
    player["pos"] = poss
    player["lap"] = poss
    player["maap"]= mpa.__name__
    obon =  [objhb,oblit,objib,npchb,nplit,npcib]
    return
#update position npc
def updnpc(fps):
    global obon
    global nbnpc
    obon[3]=[]
    obon[4]=[]
    obon[5]=[]
    for h,k in enumerate(nbnpc):
        i = k[:]
        if i[-3]<= 0:
            nbnpc[h][-3]-=1/fps
            nbnpc[h][-2],nbnpc[h][-1] = 0,0
        else:
            nbnpc[h][-3]-=1/fps
            i[1] +=i[-2]/(i[-3]*fps)
            i[2] +=i[-1]/(i[-3]*fps)
            nbnpc[h][-2]-=i[-2]/(i[-3]*fps)
            nbnpc[h][-1]-=i[-1]/(i[-3]*fps)
        stop =  [nbnpc[h][1],nbnpc[h][2]] == [i[1],i[2]] 
        nbnpc[h][1],nbnpc[h][2] = eval(eval("chara.npc."+i[0][:-2])(i[1],i[2]).mv([nbnpc[h][1],nbnpc[h][2]],[i[1],i[2]],i[7],(i[0],i[5])))
        for j in (eval("chara.npc."+i[0][:-2])(int(nbnpc[h][1]),int(nbnpc[h][2]),(i[0],player["inter"][i[0]][5]),i[7]).hb):
            obon[3].append([j,i[0]])
        for j in (eval("chara.npc."+i[0][:-2])(int(nbnpc[h][1]),int(nbnpc[h][2]),(i[0],player["inter"][i[0]][5]),i[7]).ib):
            obon[5].append(j)
        obon[4].append([eval("chara.npc."+i[0][:-2]).skn(i[7],nbnpc[h][-3],stop),int(nbnpc[h][1]),int(nbnpc[h][2]),i[3],i[4]])
    return
#display update
def blit(A,fra,mapppp,offset=(0,0)):
    global player
    screen.fill(BLK)
    mappp = mapppp.mapp
    order = [[[mappp,(0,0)]],[],[],[],[],[],[]]
    A = list(A)
    tmp = eval("chara.playable.ulo."+player["lp"]+str(fra))
    A.append([tmp,player["pos"][0],player["pos"][1]-50,None,1])
    for i in range(mappp.get_height()+2*tmp.get_height()):
        for j in A:
            if (j[2]+j[0].get_height()*j[4]+122*(1-j[4])) == i:
                if j[3] == None:
                    j[2] += 50
                    j[3] = 3
                order[j[3]].append([j[0],(j[1],j[2])])
    if mapppp.fx : 
        o = (player["pos"][0]+offset[0]-width/2+tmp.get_width()/2,player["pos"][1]+offset[1]-height/2+tmp.get_height()/2)
    elif  mappp.get_height() < height and mappp.get_width() < width :
        o = (offset[0]-width/2+mappp.get_width()/2,offset[1]-height/2+mappp.get_height()/2)
    else:
        o = ((mappp.get_width()-width)*((player["pos"][0]+tmp.get_width()/2)/mappp.get_width())+offset[0],(mappp.get_height()-height)*((player["pos"][1]+tmp.get_height()/2)/mappp.get_height())+offset[1]) 
    for i in order:
        for j in i:   
            screen.blit(j[0],(j[1][0]-o[0],j[1][1]-o[1]))
    pg.draw.rect(screen,BLK,(-mappp.get_width()/2-o[0],-mappp.get_height()/2-o[1],mappp.get_width()/2,2*mappp.get_height()))
    pg.draw.rect(screen,BLK,(mappp.get_width()-o[0],-mappp.get_height()/2-o[1],mappp.get_width()/2,2*mappp.get_height()))
    pg.draw.rect(screen,BLK,(-o[0],-mappp.get_height()/2-o[1],mappp.get_width(),mappp.get_height()/2))
    pg.draw.rect(screen,BLK,(-o[0],mappp.get_height()-o[1],mappp.get_width(),mappp.get_height()))
#interaction check
def cacahuete(objib):
    global player
    for i in objib:
        if coll(player["pos"],None,chara.playable.ulo(player).hb,[],i[0]):
            if i[1] == None:
                return i[2]
            for j in i[1]:
                if player["lp"] == j:
                    if key() == "A":
                        return i[2]
    return ""
#inventory
def invt(inv,c=0,o=(0,70),d=True):
    inv_c()
    img = pg.Surface((100,100))
    img.set_alpha(128)
    img.fill(BLK)
    if c == -1:
        screen.blit(font8.render('0'+'/'+str(len(inv)//20),True,WHT),(width/2-font8.size(str(c//20)+'/'+str(len(inv)//20))[0]/2+o[0],height/2+200+o[1]+40))
        a = 0
    else:
        screen.blit(font8.render(str(c//20)+'/'+str(len(inv)//20),True,WHT),(width/2-font8.size(str(c//20)+'/'+str(len(inv)//20))[0]/2+o[0],height/2+200+o[1]+40))
        a = c
        if d:
            pg.draw.rect(screen,BLK,(width/2-400+o[0],height/2-390+o[1],800,105))
            pg.draw.rect(screen,WHT2,(width/2-400+o[0],height/2-390+o[1],800,105),7)
            returnL(":\n".join(settings["text"].items[inv[c][0]]),(width/2-390+o[0],height/2-385+o[1]),aali=True,prnt=True,font=font4,format=780)        
    for i in range(20*(a//20),min(20*((a//20)+1),len(inv))):
        screen.blit(img,(150*(i%5)-300+width/2-50+o[0],125*((i//5)%4)-200+height/2-50+o[1]))
        screen.blit(pg.image.load(os.path.join(eval(inv[i][0]).img)),(150*(i%5)-300+width/2-50+o[0],125*((i//5)%4)-200+height/2-50+o[1]))
        if i==c:
            pg.draw.rect(screen,WHT,(150*(i%5)-300+width/2-50+o[0],125*((i//5)%4)-200+height/2-50+o[1],100,100),5)
            if player["inventory"][i][1] > 1:
                screen.blit(font8.render(str(inv[i][1]),True,BLK),(150*(i%5)-300+width/2+45-font8.size(str(inv[i][1]))[0]+o[0],125*((i//5)%4)-200+height/2+18+o[1]))
                screen.blit(font8.render(str(inv[i][1]),True,BLK),(150*(i%5)-300+width/2+41-font8.size(str(inv[i][1]))[0]+o[0],125*((i//5)%4)-200+height/2+22+o[1]))
                screen.blit(font8.render(str(inv[i][1]),True,BLK),(150*(i%5)-300+width/2+46-font8.size(str(inv[i][1]))[0]+o[0],125*((i//5)%4)-200+height/2+22+o[1]))
                screen.blit(font8.render(str(inv[i][1]),True,BLK),(150*(i%5)-300+width/2+41-font8.size(str(inv[i][1]))[0]+o[0],125*((i//5)%4)-200+height/2+18+o[1]))
                screen.blit(font8.render(str(inv[i][1]),True,BLK),(150*(i%5)-300+width/2+45-font8.size(str(inv[i][1]))[0]+o[0],125*((i//5)%4)-200+height/2+20+o[1]))
                screen.blit(font8.render(str(inv[i][1]),True,BLK),(150*(i%5)-300+width/2+41-font8.size(str(inv[i][1]))[0]+o[0],125*((i//5)%4)-200+height/2+20+o[1]))
                screen.blit(font8.render(str(inv[i][1]),True,BLK),(150*(i%5)-300+width/2+43-font8.size(str(inv[i][1]))[0]+o[0],125*((i//5)%4)-200+height/2+22+o[1]))
                screen.blit(font8.render(str(inv[i][1]),True,BLK),(150*(i%5)-300+width/2+43-font8.size(str(inv[i][1]))[0]+o[0],125*((i//5)%4)-200+height/2+18+o[1]))
                screen.blit(font8.render(str(inv[i][1]),True,WHT),(150*(i%5)-300+width/2+43-font8.size(str(inv[i][1]))[0]+o[0],125*((i//5)%4)-200+height/2+20+o[1]))
        else:
            pg.draw.rect(screen,PRPL,(150*(i%5)-300+width/2-50+o[0],125*((i//5)%4)-200+height/2-50+o[1],100,100),5)
            if inv[i][1] > 1:
                screen.blit(font8.render(str(inv[i][1]),True,PRPL),(150*(i%5)-300+width/2+43-font8.size(str(inv[i][1]))[0]+o[0],125*((i//5)%4)-200+height/2+20+o[1]))
def inventory(filter=None,drkn=True,cbt=False):
    if drkn:
        img = pg.Surface(size)
        img.set_alpha(128)
        img.fill(BLK)
        screen.blit(img,(0,0))
        del img
    a = pg.Surface(size)
    a.blit(screen,(0,0))
    c2=False
    while True:
        c=0
        while True:
            inpt = key()
            screen.blit(a,(0,0))
            clock.tick_busy_loop(60)
            if not c2:
                pg.draw.rect(screen,BLK,(width/2-350,height/2-310,300,70))
                pg.draw.rect(screen,WHT,(width/2-350,height/2-310,300,70),7)
                screen.blit(font4.render("ITEMS",True,WHT),(width/2-200-font4.size("ITEMS")[0]/2,height/2-275-font4.size("ITEMS")[1]/2))
                pg.draw.rect(screen,BLK,(width/2+50,height/2-310,300,70))
                pg.draw.rect(screen,PRPL,(width/2+50,height/2-310,300,70),7)
                screen.blit(font4.render("EQUIPEMENT",True,PRPL),(width/2+200-font4.size("EQUIPEMENT")[0]/2,height/2-275-font4.size("EQUIPEMENT")[1]/2))
            if c2:
                pg.draw.rect(screen,BLK,(width/2-350,height/2-310,300,70))
                pg.draw.rect(screen,PRPL,(width/2-350,height/2-310,300,70),7)
                screen.blit(font4.render("ITEMS",True,PRPL),(width/2-200-font4.size("ITEMS")[0]/2,height/2-275-font4.size("ITEMS")[1]/2))
                pg.draw.rect(screen,BLK,(width/2+50,height/2-310,300,70))
                pg.draw.rect(screen,WHT,(width/2+50,height/2-310,300,70),7)
                screen.blit(font4.render("EQUIPEMENT",True,WHT),(width/2+200-font4.size("EQUIPEMENT")[0]/2,height/2-275-font4.size("EQUIPEMENT")[1]/2))
                invt([x for x in player["inventory"] if eval(x[0]).type == "equipement"],c=-1,d=False)
                if inpt == "A":
                    inv = [x for x in player["inventory"] if eval(x[0]).type == "equipement"]
                    break
            elif cbt:
                invt([x for x in player["inventory"] if eval(x[0]).subtype == "combatusable"],c=-1,d=False)
                if inpt == "A":
                    inv = [x for x in player["inventory"] if eval(x[0]).subtype == "combatusable"]
                    break
            else:
                invt([x for x in player["inventory"] if eval(x[0]).type != "equipement"],c=-1,d=False)
                if inpt == "A":
                    inv = [x for x in player["inventory"] if eval(x[0]).type != "equipement"]
                    break
            if inpt == "B":
                return
            if inpt in ["DOWN","RIGHT","UP","LEFT"] : 
                c2 = not c2
            pg.display.flip()
        while inv!=[]:
            inpt = key()
            clock.tick_busy_loop(60)
            screen.blit(a,(0,0))
            invt(c=c,inv=inv)
            pg.display.flip()
            if inpt == "A" and eval(inv[c][0]).type=="usable":
                clock.tick_busy_loop(60)
                c1 = [WHT,PRPL,PRPL]
                Tn = 1
                while True:
                    clock.tick_busy_loop(60)
                    pg.draw.rect(screen,BLK,(width/2-400,height/2-320,800,105))
                    pg.draw.rect(screen,WHT2,(width/2-400,height/2-320,800,105),7)
                    inppt = key()
                    screen.blit(font4.render("USE",True,c1[0]),(width/2-390,height/2-315))
                    screen.blit(font4.render("THROW OUT",True,c1[1]),(width/2-390,height/2-315+30))
                    screen.blit(font4.render("("+str(Tn)+")",True,PRPL),(width/2-200,height/2-315+30))
                    screen.blit(font4.render("BACK",True,c1[2]),(width/2-390,height/2-315+60))
                    if inppt in ["DOWN","RIGHT"] : #below cursor mouvements
                        c1[0],c1[1],c1[2] = c1[2],c1[0],c1[1]
                    if inppt in ["UP","LEFT"]:
                        c1[0],c1[1],c1[2] = c1[1],c1[2],c1[0] 
                    if inppt=="B" or ( inppt=="A" and c1[2]==WHT ) or Tn == -1:
                        break
                    elif inppt == "A" and c1[0]==WHT:
                        pass
                    elif c1[1] == WHT and inppt =="A":
                        inpppt = ""
                        while True:
                            pg.draw.rect(screen,BLK,(width/2-400,height/2-320,800,105))
                            pg.draw.rect(screen,WHT2,(width/2-400,height/2-320,800,105),7) 
                            screen.blit(font4.render("USE",True,c1[0]),(width/2-390,height/2-315))
                            screen.blit(font4.render("THROW OUT",True,c1[1]),(width/2-390,height/2-315+30))
                            screen.blit(font4.render("("+str(Tn)+")",True,WHT),(width/2-200,height/2-315+30))
                            screen.blit(font4.render("BACK",True,c1[2]),(width/2-390,height/2-315+60))
                            if inpppt == "RIGHT":
                                pg.time.wait(100)
                                inpppt = key(True)
                                Tn=min(inv[c][1],Tn+1)
                            elif inpppt == "LEFT":
                                pg.time.wait(100)
                                inpppt = key(True)
                                Tn=max(1,Tn-1)
                            elif inpppt == "A":
                                player["inventory"][player["inventory"].index(inv[c])][1]-=Tn
                                Tn = -1
                                inv_c()
                                if c2:
                                    inv = [x for x in player["inventory"] if eval(x[0]).type == "equipement"]
                                elif cbt:
                                    inv = [x for x in player["inventory"] if eval(x[0]).subtype == "combatusable"]
                                else:
                                    inv = [x for x in player["inventory"] if eval(x[0]).type != "equipement"]
                                c = min(c,len(inv)-1)
                                break
                            elif inpppt == "B":
                                break
                            else:
                                pg.time.wait(10)
                                inpppt = key()
                            pg.display.flip()
                    pg.display.flip()
            elif inpt == "B" and cbt:
                return
            elif inpt == "B":
                break
            elif inpt == "LEFT":
                c= max(c-1,0)
            elif inpt == "UP":
                c= max(c-5,0)
            elif inpt == "RIGHT":
                c= min(c+1,len(inv)-1)
            elif inpt == "DOWN":
                c= min(c+5,len(inv)-1)
#affichage du menue deroulant charactere
def char_affiche(cursor):
    compt = 0
    inpt= key()
    for i in player["charlist"]:
        compt+=1
        pg.draw.rect( screen ,cursor[compt-1][1],(30,20 + (150+30)*(compt-1),700,150))
        pg.draw.rect( screen ,cursor[compt-1][0],(30,20 + (150+30)*(compt-1),700,150),5)
        screen.blit(font4.render(player[i]["name"]+ " lv" + str(player[i]["LV"]),True,cursor[compt-1][0]),(50,23 + (150+30)*(compt-1)))
        screen.blit(font4.render("HP : " + str(player[i]["HP"][0]) + "/" + str(player[i]["HP"][1]),True,cursor[compt-1][0]),(225,35 + (150+30)*(compt-1)))
        screen.blit(font4.render("ENERGY : " + str(player[i]["MANA"][0]) + "/" + str(player[i]["MANA"][1]),True,cursor[compt-1][0]),(225,70 + (150+30)*(compt-1)))
        screen.blit(font4.render("EXP",True,cursor[compt-1][0]),(150,110 + (150+30)*(compt-1)))
        pg.draw.rect( screen ,cursor[compt-1][1],(225,120+ (150+30)*(compt-1),300,15))
        pg.draw.rect( screen ,cursor[compt-1][0],(225,120 + (150+30)*(compt-1),300,15),5)
        pg.draw.rect( screen ,cursor[compt-1][2],(225+2.5,120 + 3 + (150+30)*(compt-1),player[i]["XP"]*30,9))
#character menu
def char_menu():
    cursor = [(WHT,BLK,PRPL)]+[(GREY,BLK,GREY)]*(len(player["charlist"])-1)
    while True:
        clock.tick_busy_loop(60)
        inpt = key()
        char_affiche(cursor)
        if inpt == "A":
            return
        if inpt == "B":
            return
        if inpt in ["DOWN", "RIGHT"]:
            cursor.insert(0,cursor[-1])
            cursor.pop(-1)
        if inpt in ["UP","LEFT"]:
            cursor.append(cursor[0])
            cursor.pop(0)
        pg.display.flip()
                
                
#general menu
def gen_menu():
    a = pg.Surface(size)
    a.blit(screen,(0,0))
    cursor =  [(WHT,BLK),(GREY,BLK),(GREY,BLK),(GREY,BLK),(GREY,BLK),(GREY,BLK)]
    cursor2 = 0
    while True:
        inpt = key()
        
        clock.tick_busy_loop(60)
        
        pg.draw.rect( screen ,cursor[0][1],(width-270,60,250,50))
        pg.draw.rect( screen ,cursor[0][0],(width-270,60,250,50), 5 )
        screen.blit(font4.render("INVENTORY",True,cursor[0][0]),(width-145-font4.size("INVENTORY")[0]/2,70))
        pg.draw.rect( screen ,cursor[1][1],(width-270,120,250,50))
        pg.draw.rect( screen ,cursor[1][0],(width-270,120,250,50), 5 )
        screen.blit(font4.render("CHARACTER",True,cursor[1][0]),(width-145-font4.size("CHARACTER")[0]/2,130))
        pg.draw.rect( screen ,cursor[2][1],(width-270,180,250,50))
        pg.draw.rect( screen ,cursor[2][0],(width-270,180,250,50), 5 )
        screen.blit(font4.render("SETTINGS",True,cursor[2][0]),(width - 145 - font4.size("SETTINGS")[0]/2,190))
        pg.draw.rect( screen ,cursor[3][1],(width-270,240,250,50))
        pg.draw.rect( screen ,cursor[3][0],(width-270,240,250,50), 5 )
        screen.blit(font4.render("SAVE",True,cursor[3][0]),(width-145-font4.size("SAVE")[0]/2,250))
        pg.draw.rect( screen ,cursor[4][1],(width-270,300,250,50))
        pg.draw.rect( screen ,cursor[4][0],(width-270,300,250,50), 5 )
        screen.blit(font4.render("LOAD",True,cursor[4][0]),(width-145-font4.size("LOAD")[0]/2,310))
        pg.draw.rect( screen ,cursor[5][1],(width-270,360,250,50))
        pg.draw.rect( screen ,cursor[5][0],(width-270,360,250,50), 5 )
        screen.blit(font4.render("QUIT",True,cursor[5][0]),(width-145-font4.size("QUIT")[0]/2,370))

        pg.display.flip()
        if inpt in ["DOWN","RIGHT"] : #below cursor mouvements
            cursor[0],cursor[1],cursor[2],cursor[3],cursor[4],cursor[5] = cursor[5],cursor[0],cursor[1],cursor[2],cursor[3],cursor[4]
        if inpt in ["UP","LEFT"]:
            cursor[0],cursor[1],cursor[2],cursor[3],cursor[4],cursor[5] = cursor[1],cursor[2],cursor[3],cursor[4],cursor[5],cursor[0]
        if inpt == "B" :
            break
        if inpt == "A" :
            if cursor[0][0] == WHT:
                inventory()
            elif cursor[1][0] == WHT:
                char_menu()
            elif cursor[2][0] == WHT:
                ST(False)
            elif cursor[3][0] == WHT:
                SaveM(True)
            elif cursor[4][0] == WHT:
                if SaveM(False):
                    return
            elif cursor[5][0] == WHT:
                pg.quit()
                quit()
            screen.blit(a,(0,0))
 

#special input    
def regularinput(key):
    if key == "X":
        gen_menu()
#import item in inventory
def item_get(iid , No=1 , diag=True):
    if diag:
        textbox(settings["text"]().itmget(iid,No))
    if eval(iid).stack:
        try :
            ind =  [ x[0] for x in player["inventory"] ].index(iid)
            player["inventory"][ind][1] += No
            player["inventory"][ind][2] = player["tsst"]
            player["tsst"]+=1
        except ValueError:
            player["inventory"].append([iid,No,player["tsst"]])
    else:
        for i in range(No):
            player["inventory"].append([iid,1,player["tsst"]])
            player["tsst"]+=1
#inventory clear (removes items w/ 0 qty)
def inv_c():
    try:
        while True:
            ind = [ x[1] for x in player["inventory"] ].index(0)
            player["inventory"].pop(ind)
    except ValueError:
        return
#object 
def itm_c(iid): 
    return iid in [ x[0] for x in player["inventory"] ]
#npc movement
def npcmv(fps):
    global nbnpc 
    def randomv(fps,a,b,c,i):
        if i[-3] < -1 and random.random() < 1/(a*fps):
            i[-4] = random.choice(["UP","DOWN","LEFT","RIGHT"])
            i[-3] = random.random()*b
            i[-2] = i[-3]*c*((i[-4]=="RIGHT")-(i[-4]=="LEFT"))
            i[-1] = i[-3]*c*((i[-4]=="DOWN")-(i[-4]=="UP"))
        return(i)
    for i in nbnpc:
        i = eval(i[6])
#interaction update
def didn(id0,id1):
    global player
    player["inter"][id0][5]=id1

def game(cnt): #game loop(put everything in there(level events,random encounters...))
    global player
    global nbnpc
    global obon
    fra = "P"
    timer = 0
    game_over = False
    mapsw(eval("maps."+player['maap']),player['pos'])
    if not cnt:  
        save()
    while not game_over: 
        exec(cacahuete(obon[2]+obon[5]))
        ky,fra,timer = mv(fra,timer)
        player["pos"] = coll1(player["pos"],player["lap"],"chara.playable.ulo(player).hb",eval("maps."+player["maap"]+".hbmp"),obon[0]+[x[0] for x in obon[3]])
        updnpc(60)
        npcmv(60)   
        clock.tick_busy_loop(60)
        regularinput(ky)
        blit(obon[4]+obon[1],fra,eval("maps."+player['maap']))
        pg.display.flip()
#all the game 
while True:
    cnt = False
    exec(MePr())
    game(cnt)
