Beispiel #1
0
def getcolorsconfig(requiredkeys):
    sections = Core.readconfigfile(Core.CONFIGDIR+"colors.ini")
    #apply specific treatments for special sections
    draworder = []
    if ("display" in sections):
        draworder = sections["display"]["order"].split(" ")
        del sections["display"]
    axesgrid = 10
    if ("axes" in sections and "grid" in sections["axes"]):
        axesgrid = sections["axes"]["grid"]
        del sections["axes"]["grid"]
    newsections = {}
    refs = []
    #first pass: get colors from each line, if possible
    for sectionname in sections:
        configs = sections[sectionname]
        newconfigs = {}
        for configname in configs:
            rgba = configs[configname].split(" ")
            ext = configs[configname].split(".")
            if (len(rgba) in [3,4]):
                if (len(rgba) == 3):
                    rgba.append(255)
                (r, g, b, a) = rgba
                try:
                    (r, g, b, a) = (int(r), int(g), int(b), int(a))
                    if not (isint8(r) and isint8(g) and isint8(b) and isint8(a)):
                        if (not isint8(r)):
                            printf("Attention: "+str(sectionname)+"."+str(configname)+": r doit être compris entre 0 et 255 inclus")
                        if (not isint8(g)):
                            printf("Attention: "+str(sectionname)+"."+str(configname)+": g doit être compris entre 0 et 255 inclus")
                        if (not isint8(b)):
                            printf("Attention: "+str(sectionname)+"."+str(configname)+": b doit être compris entre 0 et 255 inclus")
                        if (not isint8(a)):
                            printf("Attention: "+str(sectionname)+"."+str(configname)+": a doit être compris entre 0 et 255 inclus")
                    else:
                        newconfigs[configname] = (r, g, b, a)
                except Exception as e:
                    printf("Attention: "+str(sectionname)+"."+str(configname)+": format non reconnu")
                    pass
            elif (len(ext) == 2):
                refs.append((sectionname, configname, ext))
            else:
                printf("Attention: "+str(sectionname)+"."+str(configname)+": format non reconnu")
                pass
        newsections[sectionname] = newconfigs
    oldreflen = -1
    #second pass: resolve as many cross-references as possible
    while (len(refs) != 0 and len(refs) != oldreflen):
        i = 0
        oldreflen = len(refs)
        while (i < oldreflen):
            try:
                (sectionname, configname, (extsection, extconfig)) = refs[i]
                if (extsection in newsections and extconfig in newsections[extsection]):
                    newsections[sectionname][configname] = newsections[extsection][extconfig]
                    refs.pop(i)
                    i = oldreflen
            except Exception as e:
                #not added yet, or impossible to add => do nothing
                pass
            i += 1
    if (len(refs) > 0):
        printf("Attention: les références suivantes ne peuvent pas être résolues:")
        for ref in refs:
            (sn, cn, (esn, ecn)) = ref
            printf(str(sn)+"."+str(cn)+" -> "+str(esn)+"."+str(ecn))
    #remove remaining special section if it is (I do it here to use previous useful treatment for it)
    axescolor = {"main":(255,255,0,92),"secondary":(255,255,255,32)}
    if ("axes" in newsections):
        for key in axescolor:
            if (key not in newsections["axes"]):
                newsections["axes"][key] = axescolor[key]
        axescolor = newsections["axes"]
        del newsections["axes"]
    try:
        axescolor["grid"] = int(axesgrid)
    except Exception as e:
        printf("Erreur: axes.grid: paramètre invalide")
        return
    #third pass: ensure each used key exists
    defaultcolors = {"default":(0,0,170,255),"onexplore":(200,0,0,255),"ontarget":(0,192,0,255)}
    #use background as default as possible
    if ("background" in newsections):
        for key in defaultcolors:
            if (key in newsections["background"]):
                defaultcolors[key] = newsections["background"][key]
    for key in list(requiredkeys)+["background"]:
        if (key not in newsections):
            newsections[key] = defaultcolors
            printf("Attention: "+str(key)+": section manquante")
        else:
            if ("default" not in newsections[key]):
                printf("Attention: "+str(key)+".default: paramètre manquant")
                newsections[key]["default"] = defaultcolors["default"]
            if ("onexplore" not in newsections[key]):
                printf("Attention: "+str(key)+".onexplore: paramètre manquant")
                newsections[key]["onexplore"] = defaultcolors["onexplore"]
            if ("ontarget" not in newsections[key]):
                printf("Attention: "+str(key)+".ontarget: paramètre manquant")
                newsections[key]["ontarget"] = defaultcolors["ontarget"]
    #fourth pass: we need to have all config names for drawing, get missings if there are
    for key in newsections:
        if (key not in draworder):
            draworder.append(key)
    return (newsections, axescolor, draworder)
Beispiel #2
0
def load(playername):
    return (readcoordsfile(Core.prefix(playername)+".txt"), readcoordsfile(Core.prefix(playername)+".objectifs.txt"), Core.readconfigfile(Core.prefix(playername)+".infos.ini"))
Beispiel #3
0
def Main():
    if (not os.path.isdir(CONFIGDIR)):
        os.mkdir(CONFIGDIR)
    if (not os.path.isdir(SAVEDIR)):
        os.mkdir(SAVEDIR)

    planets = Data.loadPlanets(CONFIGDIR+"coords_planets.txt")
    planet_names = list(planets.keys())
    reservedwords = ["zone", "d", "help"] + planet_names

    commands = Core.readconfigfile(CONFIGDIR+"words.ini")
    
    #make sure that dictionnary contains all used keys and for all keys, each required subdictionnary is given
    requiredkeys = {"map":[], "save":[], "target":["delallexplored","removeall"], "view":[], "exit":[], "set-terre":[]}
    errmsg = ""
    for key in requiredkeys:
        if (key not in commands):
            commands[key] = {"words":key}
            errmsg += "- section "+key+" non trouvée\n"
        elif ("words" not in commands[key]):
            commands[key]["words"] = key
            errmsg += "- aucun mot pour la commande "+key+"\n"
        for subkey in requiredkeys[key]:
            if (subkey not in commands[key]):
                commands[key][subkey] = subkey
                errmsg += "- paramètre manquant dans la commande "+key+": "+subkey+"\n"
    #
    #get set of words for each command (instead of space-separated string)
    #keep only non reserved words, but at least one
    for key in commands:
        for subkey in commands[key]:
            commands[key][subkey] = set(commands[key][subkey].split())
            size = len(commands[key][subkey])
            Core.removefromlist(commands[key][subkey], reservedwords)
            if (len(commands[key][subkey]) != size):
                if (subkey == "words"):
                    errmsg += "- des mots réservés ont été supprimés pour la commande "+key+"\n"
                else:
                    errmsg += "- des mots réservés ont été supprimés pour le paramètre "+subkey+" dans la commande "+key+"\n"
            if (len(commands[key][subkey]) == 0):
                if (subkey == "words"):
                    commands[key][subkey].add(key)
                    errmsg += "- aucun mot pour la commande "+key+"\n"
                else:
                    commands[key][subkey].add(subkey)
                    errmsg += "- paramètre manquant dans la commande "+key+": "+subkey+"\n"
    #
    #use some standard words to exit prompt
    exitwords_reserved = ("quit", "exit")
    for exit_word in exitwords_reserved:
        if (not exit_word in commands["exit"]["words"]):
            commands["exit"]["words"].add(exit_word)
    #
    if (len(errmsg) > 0):
        printf("Problème(s) lors de la lecture du fichier words.ini:")
        printf(errmsg)
    playername = ""
    if (len(sys.argv) >= 2):
        playername = sys.argv[1].strip().lower()
    if (Core.isforbidden(playername) or playername in exitwords_reserved):
        playername = raw_input("Entrez votre pseudo: ")
    playername = playername.strip().lower()
    if (Core.isforbidden(playername)):
        printf("Erreur: ce pseudo est interdit")
        sys.exit(0)
    elif (playername in exitwords_reserved):
        sys.exit(0)
    playerdata = Data.load(playername)
    settings = playerdata[2]
    if (playername not in settings):
        settings[playername] = {}
    settings = settings[playername]
    if ("terre" in settings):
        planet_names = addTerre(settings, settings["terre"].split(), planets)
    Str = ""
    Strlist = []
    printf('Tapez "help" pour obtenir de l\'aide')
    try:
        exit = False
        while (not exit and not Core.oneIn(commands["exit"]["words"], Strlist)):
            Str = raw_input("> ").strip().lower()
            if (Str == ""):
                continue
            Strlist = Str.split(" ")
            try:
                if (Core.oneIn(commands["exit"]["words"], Strlist)):
                    exit = True
                if ("help" in Strlist):
                    print_help(Strlist, commands, planet_names, playername)
                elif (Core.oneIn(commands["map"]["words"], Strlist)):
                    Map.makeMap(playername, playerdata, planets)
                elif (Core.oneIn(commands["save"]["words"], Strlist)):
                    Data.save(playername, playerdata)
                elif (Core.oneIn(commands["view"]["words"], Strlist)):
                    os.system(Map.getMapFilename(playername))
                elif (Core.oneIn(commands["target"]["words"], Strlist) and not exit):
                    printf('Entrez vos nouveaux objectifs:')
                    while (not Core.oneIn(commands["exit"]["words"], Strlist)):
                        Str = raw_input("==> ").strip().lower()
                        if (Str == ""):
                            continue
                        Strlist = Str.split(" ")
                        if ("help" in Strlist):
                            printf("Vous êtes dans le mode d'édition des objectifs.")
                            printf("Dans ce mode, les commandes disponibles sont les suivantes:")
                            printf("- afficher ce message (tapez \"help\")")
                            printf("- revenir au mode d'exploration: tapez l'un des mots suivants: "+printwords(commands["exit"]["words"]))
                            printf('- tapez "x y" pour marquer le secteur aux coordonnées (x, y) comme objectif.')
                            printf('- tapez "zone x1 y1 x2 y2" pour marquer comme objectif chaque secteur situé dans le rectangle décrit par les coordonnées (x1, y1) et (x2, y2).')
                            printf("- entrez le nom d'une planète pour marquer chacun de ses secteurs comme objectif.")
                            printf('- liste des planètes: '+printwords(planet_names))
                            printf('- dans les commandes précédentes, l\'option "d" a pour effet de supprimer un/des secteur(s) de la liste des objectifs.')
                            printf("- vider la liste des objectifs, tapez l'un des mots suivants: "+printwords(commands["target"]["removeall"]))
                            printf("- retirer tout secteur exploré de la liste des objectifs, tapez l'un des mots suivants: "+printwords(commands["target"]["delallexplored"]))
                        elif (Core.oneIn(commands["target"]["removeall"], Strlist)):
                            Data.cleartargets(playerdata)
                        elif (Core.oneIn(commands["target"]["delallexplored"], Strlist)):
                            Data.cleantargets(playerdata)
                        elif (Core.oneIn(commands["exit"]["words"], Strlist)):
                            pass #nothing to do
                        else:
                            (coords, explore) = parsecoords(Str, Strlist, planet_names, planets)
                            if (explore):
                                Data.addtarget(playerdata, coords)
                            else:
                                Data.deltarget(playerdata, coords)
                    Strlist = [] #don't exit immediately after that
                elif (Core.oneIn(commands["set-terre"]["words"], Strlist) and not exit):
                    printf('Entrez les coordonnées de votre terre:')
                    while (not Core.oneIn(commands["exit"]["words"], Strlist)):
                        Str = raw_input("==> ").strip().lower()
                        if (Str == ""):
                            continue
                        Strlist = Str.split(" ")
                        if ("help" in Strlist):
                            printf("Vous êtes dans le mode d'édition de la terre.")
                            printf("Dans ce mode, les commandes disponibles sont les suivantes:")
                            printf("- afficher ce message (tapez \"help\")")
                            printf("- revenir au mode d'exploration: tapez l'un des mots suivants: "+printwords(commands["exit"]["words"]))
                            printf("- indiquer l'emplacement de la terre: tapez \"x y\" en remplaçant x et y par les coordonnées indiquées par la carte PID")
                        elif (Core.oneIn(commands["exit"]["words"], Strlist)):
                            pass #nothing to do
                        else:
                            (coords, explore) = parsecoords(Str, Strlist, planet_names, planets)
                            if (len(coords) != 1):
                                printf("Indiquez les coordonnées écrites sur la carte PID")
                            else:
                                planet_names = addTerre(settings, coords[0], planets)
                                break
                    Strlist = [] #don't exit immediately after that
                elif (Core.oneIn(commands["exit"]["words"], Strlist)):
                    pass #nothing to do
                else:
                    (coords, explore) = parsecoords(Str, Strlist, planet_names, planets)
                    if (explore):
                        Data.explore(playerdata, coords)
                    else:
                        Data.unexplore(playerdata, coords)
            except Exception as e:
                traceback.print_exc()
    except KeyboardInterrupt as e:
        pass
    except Exception as e:
        traceback.print_exc()