Exemple #1
0
    def callListener(self, data):
        if data is None:
            return

        result = self.engine.logCalls(data)
        if self.engine.isReadyForNextPlayer:
            clearScreen()
            if result == 0:
                if self.engine.previousPlayer().name == self.localPlayer.name:
                    print("Nobody thought you were bluffing :)")
                else:
                    print(f"Nobody thought {self.engine.previousPlayer().name} was bluffing")
            elif result == -1:
                if self.engine.previousPlayer().name == self.localPlayer.name:
                    print("You were called on your bluff! You just picked up the pile :(")
                else:
                    print(f"{self.engine.previousPlayer().name} was bluffing!")
            elif result == 1:
                if self.engine.previousPlayer().name == self.localPlayer.name:
                    print("People thought you bluffed, but they were wrong :)")
                else:
                    print(f"{self.engine.previousPlayer().name} was not bluffing! All players who thought they were have divided the pile amongst themselves")
            print()
            self.callStream.close()

            if self.engine.isGameOver():
                self.endGame()
            
            self.printTurns()
            if self.takeTurnAfterCalls:
                self.takeTurn()
Exemple #2
0
def loadGame():
    global saveFile
    _invalid = ''
    savefiles = glob.glob(os.path.join(scriptDirPath, 'saves', '*'))
    saves = [os.path.basename(file) for file in savefiles]
    saves.extend(['-EMPTY-', '-EMPTY-', '-EMPTY-'])

    while True:
        _1, _2, _3 = saves[:3]
        clearScreen()
        print(display['loadgame'].format(_1, _2, _3) + _invalid)
        _invalid = ''

        choice = userInput()
        if choice not in '123db':
            _invalid = '\n    [ Please choose valid option ]\n'
        elif choice == 'd':
            saves = deleteSave(saves)
        elif choice == 'b':
            return 'back'
        elif int(choice) > len(savefiles):
            _invalid = '\n    [ This save file is empty ]\n'
        else:
            saveFile = savefiles[int(choice) - 1]
            return 'play'
Exemple #3
0
def deleteSave(savelist, fromSaveError=False):
    _invalid = ''
    while True:
        _1, _2, _3 = savelist[:3]
        clearScreen()
        print(display['deletesave'].format(_1, _2, _3) + _invalid)
        _invalid = ''

        choice = userInput()
        if choice not in '123b':
            _invalid = '\n    [ Please choose valid option ]\n'
        elif choice == 'b':
            break
        elif int(choice) > len(savelist) - 3:
            _invalid = '\n    [ This save file is empty ]\n'
        else:
            clearScreen()
            print(display['confirm'].format('DELETE'))
            while True:
                confirm = userInput()
                if confirm == 'n':
                    break
                elif confirm == 'y':
                    deleteFile(
                        os.path.join(scriptDirPath, 'saves',
                                     savelist[int(choice) - 1]))
                    savelist.pop(int(choice) - 1)
                    if fromSaveError: return
                    break

    return savelist
def battleStart():
    gameWinner = None
    loadGame()
    while gameWinner == None:
        loadGame()
        displayGameStatus()
        playerOneTurn()

        loadGame()
        gameWinner = checkWinner()
        if gameWinner != None:
            break

        loadGame()
        displayGameStatus()
        playerTwoTurn()

        loadGame()
        gameWinner = checkWinner()
        if gameWinner != None:
            break
    utils.clearScreen()
    winner = None
    if gameWinner == 'player_one':
        winner = playerOneName
    elif gameWinner == 'player_two':
        winner = playerTwoName
    input(winner + " wins the game! Press any key to continue...")
    utils.clearScreen()
    print("Welcome to PSB Battle Game!")
    print("\n[N]ew game \n[R]esume game \n[H]ow to play \n[E]xit\n")
def randomNumberGenerator(nReturn):
    for i in range(0, nReturn):
        clearScreen()
        print("El generador se encuentra en ejecución")
        print(str(i) + " de " + str(nReturn) + " números generados.")
        print("Para visualizar el resultados abra el archivo numbers.txt")
        while True:
            text = getText()
            binary = ''.join(format(ord(i), 'b') for i in text)

            binary = xorOne(binary)
            binary = xorTwo(binary)
            binary = xorOne(binary)
            binary = xorTwo(binary)

            totalBcd = ""
            for i in range(0, len(binary) // 4):
                newSubstring = binary[slice(i * 4, i * 4 + 4)]
                newBcd = int(newSubstring, 2)
                if newBcd <= 9:
                    totalBcd += str(newBcd)

            if len(totalBcd) >= 4:
                number = "0." + totalBcd[slice(0, 4)]
                f = open("numbers.txt", "a+")
                f.write(str(number) + "\n")
                f.close()
                break
Exemple #6
0
 def displayGame(self, timePerTurn: float = 0.5):
     i = 1
     for state in self.getAllStates():
         utils.clearScreen()
         state.printMap()
         print("%d / %d" % (i, len(self.actions)+1))
         i += 1
         time.sleep(timePerTurn)
Exemple #7
0
def quitGame():
    clearScreen()
    print(display['confirm'].format('QUIT'))

    if userInput() == 'y':
        return 'quit'
    else:
        return 'back'
Exemple #8
0
 def createRoom(self):
     success, message, data = firebaseutils.createRoom(self.localPlayer.name)
     if not success:
         print("Could not create room key. Please try again")
         os._exit(1)
     clearScreen()
     print(message)
     return data['roomKey']
Exemple #9
0
def login():
    utils.clearScreen()
    logininfo = {}
    logininfo = draw.showLoginUsrPsswdMenu()
    if (users.validateLogin(logininfo[globals.field_nickname], logininfo[globals.field_password]) == False):
        login()
    else:
        files.createFilesPath()
        return
def main(args=None):
    parser = argparse.ArgumentParser(description='Play a game of Tic Tac Toe')
    parser.add_argument('--mode',
                        type=str,
                        default='s',
                        choices=['s', 't'],
                        help='Mode: s(single player):default, t(two-player)')
    mode = parser.parse_args().mode
    utils.clearScreen()
    game = tic_tac_toe(mode)
Exemple #11
0
 def shouldStartGame(stillWaiting):
     if not stillWaiting:
         clearScreen()
         print("The host has started the game.")
         startStream.close()
         playerStream.close()
         try:
             self.loadGame()
         except firebaseutils.FirebaseError:
             self.exitWithError()
Exemple #12
0
    def startGame(self):
        hands = self.engine.listHands()
        self.engine.orderPlayers()

        firebaseutils.startGame(self.roomKey, hands, self.engine.playerList)

        clearScreen()
        self.printTurns()

        self.turnStream = Stream(self.turnListener)
        firebaseutils.listenForTurn(self.turnStream, self.roomKey)
def displayGameStatus():
    utils.clearScreen()
    print(playerOneName + '\'s Team')
    for character in playerOneTeam:
        if character['status'] == 'alive':
            print(character['name'] + ' - ' + 'Health: ' +
                  str(character['attributes']['health']))
    print('\n' + playerTwoName + '\'s Team')
    for character in playerTwoTeam:
        if character['status'] == 'alive':
            print(character['name'] + ' - ' + 'Health: ' +
                  str(character['attributes']['health']))
Exemple #14
0
def showUserMenu():
    op = -1
    utils.clearScreen()
    print(
        "-------------------------------- MENU USUARIOS -------------------------------"
    )
    print("    Opções:")
    print("        1 - Cadastrar usuário")
    print("        2 - Listar usuários")
    print("        3 - Remover arquivo de usuários")
    op = input("Opção selecionada: ")
    return int(op)
Exemple #15
0
def showFileMenu():
    op = -1
    utils.clearScreen()
    print(
        "-------------------------------- MENU ARQUIVOS -------------------------------"
    )
    print("    Opções:")
    print("        1 - Enviar arquivo")
    print("        2 - Ler arquivo")
    print("        2 - Listar meus arquivos enviados")
    print("        3 - Listar meus arquivos recebidos")
    op = input("Opção selecionada: ")
    return int(op)
Exemple #16
0
def tutorial():
    tutplayer = Player('Tutorial')
    tutmap = Map(tut=True)
    tutplayer.linkMap(tutmap)
    while True:
        clearScreen()
        tutmap.update()
        choice = userInput()
        if choice == 'q':
            break
        elif choice in 'wasd':
            tutplayer.move(choice)

    del tutmap, tutplayer
Exemple #17
0
def showKeyMenu():
    op = -1
    utils.clearScreen()
    print(
        "--------------------------------- MENU CHAVES --------------------------------"
    )
    print("    Opções:")
    print("        1 - Gerar chaves publica/privada")
    print("        2 - Setar tamanho de bits da chave RSA")
    print("        3 - Listar minhas chaves")
    print("        4 - Remover minhas chaves")
    print("        5 - Mostrar chave publica de outro usuario")
    op = input("Opção selecionada: ")
    return int(op)
Exemple #18
0
    def takeTurn(self):
        if self.engine.currentPlayer().name != self.localPlayer.name:
            return

        cardHash = self.engine.takeTurn()
        clearScreen()

        firebaseutils.clearCalls(self.roomKey)
        firebaseutils.logTurn(self.roomKey, cardHash)

        print("Waiting for other players to call your bluff or let you pass")

        self.takeTurnAfterCalls = False
        self.callStream = Stream(self.callListener)
        firebaseutils.listenForCall(self.callStream, self.roomKey)
Exemple #19
0
    def runGame(self, gm: GameMap = None, timePerTurn: float = 0):

        if gm is None:
            gm = self.initGameMap()
        gh = GameHistory(gm)

        if timePerTurn > 0:
            utils.clearScreen()
            gm.printMap()
            time.sleep(timePerTurn)

        turn = 0
        while True:

            if self.checkGameEnd(gm):
                break

            playerPos = [pos for pos in gm.data if gm.data[pos] != None]

            random.shuffle(playerPos)

            for pos in playerPos:

                player = gm.data[pos]

                if player is None:
                    continue

                vision = gm.getVision(pos, 5)
                gh.actions.append((pos, player.ai.getAction(vision)))
                gh.applyAction(gm)

            turn += 1

            if timePerTurn > 0:
                utils.clearScreen()
                gm.printMap()
                print("turn: " + str(turn))
                time.sleep(timePerTurn)

        if timePerTurn > 0:
            print("done in %d turns" % turn)

        return gh
Exemple #20
0
    def start(self):
        self.printHeader()

        name = self.enterName()
        self.localPlayer = Player(name)
        
        self.printWelcome(name)
        choice = self.handleEntrance()
        clearScreen()
        if choice == 1:
            success = False
            while not success:
                self.roomKey = input("Please enter your room key: ")
                success = self.joinRoom()
        else:
            self.localPlayer.isHost = True
            self.roomKey = self.createRoom()

        self.engine = Engine(self.localPlayer)
        self.waitForOthers()
Exemple #21
0
def showMainMenu():
    op = -1
    utils.clearScreen()
    #print(globals.current_user_nickname)
    #print(globals.current_user_name)
    #print(globals.current_user_email)
    #print(globals.my_public_key)
    #print(globals.my_private_key)
    #print(globals.path_public_key + globals.my_public_key)
    #print(globals.path_private_key + globals.my_private_key)
    print(
        "------------------------------------ MENU ------------------------------------"
    )
    print("    Opções:")
    print("        1 - Usuários")
    print("        2 - Chaves")
    print("        3 - Arquivos")
    print("        0 - Sair")
    op = input("Opção selecionada: ")
    return int(op)
Exemple #22
0
def newGame():
    global saveFile
    savefiles = glob.glob(os.path.join(scriptDirPath, 'saves', '*'))
    saves = [os.path.basename(file) for file in savefiles]
    saves.extend(['-EMPTY-', '-EMPTY-', '-EMPTY-'])

    clearScreen()
    print(display['newgame']['name'], end='')
    name = input()

    if len(savefiles) == 3:
        clearScreen()
        print(display['newgame']['saveerror'])
        while True:
            choice = userInput()
            if choice == 'y':
                deleteSave(saves, True)
                break
            elif choice == 'n':
                return 'back'

    clearScreen()
    print(display['newgame']['tutorial'].format(name))
    while True:
        choice = userInput()
        if choice == 'y':
            tutorial()
            break
        elif choice == 'n':
            break

    saveFile = os.path.join(scriptDirPath, 'saves', name)
    open(saveFile, 'x').close()
    return 'play'
Exemple #23
0
def mainMenu() :
    print(display['title'])
    while True :
        if userInput() == 's' : break

    _invalid = ''
    while True :
        clearScreen()
        print(display['mainmenu'] + _invalid)
        _invalid = ''

        choice = userInput()
        if choice not in 'nldq' :
            _invalid = '\n    [ Please choose valid option ]\n'
            continue
        result = menuOptions[choice]()
        if result == 'quit' :
            clearScreen(); return False
        elif result == 'play' :
            return True
        elif result == 'back' :
            continue
Exemple #24
0
def difficultyLevel():
    global difficulty
    _invalid = ''
    indicator = [
        ['>', ' '],  # easy
        [' ', '>']
    ]  # hard

    while True:
        clearScreen()
        print(display['difficultylevel'].format(
            indicator[0][difficulty], indicator[1][difficulty]) + _invalid)

        choice = userInput()
        if choice == 'e':
            difficulty = 0
        elif choice == 'h':
            difficulty = 1
        elif choice == 'b':
            return 'back'
        else:
            _invalid = '\n    [ Please choose valid option ]\n'
def build(numberOfCharacters, player, playerName):
    count = 0
    while count < numberOfCharacters:
        utils.clearScreen()
        count += 1
        ordinal = None
        if (count == 1):
            ordinal = 'first'
        elif (count == 2):
            ordinal = 'second'
        elif (count == 3):
            ordinal = 'third'
        elif (count == 4):
            ordinal = 'fourth'
        elif (count == 5):
            ordinal = 'fifth'
        print("Nice to meet you " + playerName + ", let's build your team!\n")
        print(
            """[T]roll - A strong attack but careless monster that has 50% chance of missing its target\n[K]night - A soldier with decent attack and strong defense\n[M]age - A spell caster with low attack and defense\n"""
        )
        characterClassInput = str(
            input("Pick a class for your " + ordinal + " character: "))
        characterNameInput = str(input("What is your character's name?: "))
        playerUnits = {
            "character_class": characterClassInput.upper(),
            "character_name": characterNameInput
        }
        if (player == 1):
            playerOneTeam.append(playerUnits)
        elif (player == 2):
            playerTwoTeam.append(playerUnits)

    if (player == 1):
        return playerOneTeam
    elif (player == 2):
        return playerTwoTeam
    def two_player(self, board):
        '''
		Play in 2 player mode
		'''
        keyboardIndexMapping = constants.keyboardIndexMapping
        playerOne, playerTwo, playerOneChar, playerTwoChar, whichPlayerFirst = utils.getTwoPlayerDetails(
        )
        move_mapping = {playerOne: playerOneChar, playerTwo: playerTwoChar}

        if whichPlayerFirst == 1:
            chance = playerOne
        else:
            chance = playerTwo

        while (utils.check_win(board, playerOneChar, playerTwoChar)[0] == 0):
            utils.clearScreen()
            utils.display_board(board)
            print(chance + ": Your chance")
            index = int(input())
            if index > 9 or index < 1:
                utils.clearScreen()
                continue
            index = keyboardIndexMapping[index]
            if (board[index] != '-'):
                continue
            board[index] = move_mapping[chance]
            if (chance == playerOne):
                chance = playerTwo
            else:
                chance = playerOne
        [isWin, whoWon] = utils.check_win(board, playerOneChar, playerTwoChar)
        if (isWin == 2):
            utils.clearScreen()
            utils.display_board(board)
            print("It's a tie")
        if (isWin == 1):
            utils.clearScreen()
            utils.display_board(board)
            if (whoWon == playerOneChar):
                print(playerOne + " won!")
            else:
                print(playerTwo + " won!")
            break
    utils.clearScreen()
    winner = None
    if gameWinner == 'player_one':
        winner = playerOneName
    elif gameWinner == 'player_two':
        winner = playerTwoName
    input(winner + " wins the game! Press any key to continue...")
    utils.clearScreen()
    print("Welcome to PSB Battle Game!")
    print("\n[N]ew game \n[R]esume game \n[H]ow to play \n[E]xit\n")


# Game Menu

utils.clearScreen()
print("Welcome to PSB Battle Game!")
print("\n[N]ew game \n[R]esume game \n[H]ow to play \n[E]xit\n")

while True:
    chosenMenu = str(input("Choose an option: "))
    # New Game
    if chosenMenu.lower() == 'n':
        if os.path.exists("game.json"):
            os.remove("game.json")
        shutil.copyfile('init/player_vs_player.json', 'game.json')
        # Player One
        utils.clearScreen()
        playerOneName = str(input("Hello stranger, what is your name?: "))
        playerOne.append(playerOneName)
        utils.clearScreen()
Exemple #28
0
def playGame(savefile):
    clearScreen()
    print('yet to design LOL')
    print(savefile)
Exemple #29
0
def addExec(cmakelistsFile):
    # Extrai o diretório do arquivo CMakeLists.txt.
    cmakelistsPath = os.path.dirname(cmakelistsFile)

    # Espera o usuário informar a pasta que contém os arquivos do novo projeto.
    while True:
        utils.clearScreen()

        print("\n  Selecione a pasta com os arquivos do novo projeto.", end="")

        # Inicia um diálogo para selecionar a pasta do novo projeto.
        newExecFolder = fd.askdirectory(
            initialdir=cmakelistsPath,
            title="Selecione a pasta do novo projeto")

        # Verifica se é uma pasta válida.
        # Deve ser uma pasta dentro da mesma pasta do arquivo CMakeLists.txt.
        if not utils.isInsideFolder(newExecFolder, cmakelistsPath):
            print("\n\n  A pasta informada não é válida!")
            print(
                "  Ela deve ser uma pasta dentro de {}".format(cmakelistsPath))
            input("\n  Pressione [ENTER] para tentar novamente...")
            continue

        # Se chegou até aqui, a pasta é válida.
        break

    # Lista os arquivos disponíveis na pasta do projeto,
    # que podem ser inclusos como parte do código.
    availableFiles = utils.fileTree(newExecFolder)

    # Recebe os arquivos que foram selecionados para fazer parte do código.
    selectedFiles = []

    # Espera o usuário selecionar os arquivo
    while True:
        try:
            utils.clearScreen()

            print(
                "\n  Arquivos existentes na pasta {}:\n".format(newExecFolder))

            # Lista os arquivos dentro da pasta do projeto a ser construído.
            for n, i in enumerate(availableFiles):
                print("  X {:3d}. {}".format(
                    n, i)) if n in selectedFiles else print(
                        "    {:3d}. {}".format(n, i))

            print("\n  Quais arquivos acima fazem parte do projeto?")
            print(
                "\n  Para incluir ou desfazer inclusão, informe o número referente ao arquivo."
            )
            print(
                "  Devem ser selecionados na ordem em que devem ser inclusos.")
            print("  Quando estiver pronto, apenas pressione [ENTER].")

            # Recebe o arquivo a ser adicionado ou descartado.
            fileToAdd = input("\n  Índice do arquivo: ")

            # Se nenhum arquivo for informado, pula esta etapa.
            if not fileToAdd:
                if not selectedFiles:
                    print("\n  Pelo menos um arquivo deve ser selecionado!")
                    input("\n  Pressione [ENTER] para tentar novamente...")
                    continue

                break

            fileToAdd = int(fileToAdd)

            # Verifica se o valor informado está presente na lista.
            if not fileToAdd in range(0, len(availableFiles)):
                raise ValueError()

            selectedFiles.remove(
                fileToAdd
            ) if fileToAdd in selectedFiles else selectedFiles.append(
                fileToAdd)
        # Caso a opção informada seja inválida.
        except ValueError:
            input(
                "\n  Opção inválida! Pressione [ENTER] para tentar novamente.")

    # Bibliotecas disponíveis.
    libs = utils.fileTree(cmakelistsPath + os.sep + "common", ".hpp", 1)

    # Retira a extensão das bibliotecas.
    for i, lib in enumerate(libs):
        libs[i] = os.path.splitext(lib)[0]

    # Recebe as bibliotecas que serão adicionadas ao novo projeto.
    newExecLibs = []

    # Espera o usuário informar as bibliotecas externas que deseja incluir ao projeto.
    while True:
        try:
            utils.clearScreen()

            print(
                "\n  Bibliotecas disponíveis para incluir ao seu novo projeto:\n"
            )

            # Lista as bibliotecas disponíveis.
            for n, i in enumerate(libs):
                print("  X {:d}. {}".format(n,
                                            i)) if n in newExecLibs else print(
                                                "    {:d}. {}".format(n, i))

            print(
                "\n  Deseja incluir alguma? Isto é opcional. Depende do seu projeto."
            )
            print(
                "\n  Para incluir ou desfazer inclusão, informe o número referente à biblioteca."
            )
            print("  Quando estiver pronto, apenas pressione [ENTER].")

            # Recebe a biblioteca a ser adicionada ou descartada.
            libToAdd = input("\n  Índice da biblioteca: ")

            # Se nenhuma biblioteca for informada, pula esta etapa.
            if not libToAdd:
                break

            libToAdd = int(libToAdd)

            # Verifica se o valor informado está presente na lista.
            if not libToAdd in range(0, len(libs)):
                raise ValueError()

            newExecLibs.remove(
                libToAdd) if libToAdd in newExecLibs else newExecLibs.append(
                    libToAdd)
        # Caso a opção informada seja inválida.
        except ValueError:
            input(
                "\n  Opção inválida! Pressione [ENTER] para tentar novamente.")

    # Ordena as bibliotecas.
    newExecLibs.sort()

    # Bibliotecas externas disponíveis.
    externalLibs = [
        "ANTTWEAKBAR_116_OGLCORE_GLFW", "assimp", "BulletCollision",
        "BulletDynamics", "LinearMath"
    ]

    # Recebe as bibliotecas externas que serão adicionadas ao novo projeto.
    newExecExternals = []

    # Espera o usuário informar as bibliotecas externas que deseja incluir ao projeto.
    while True:
        try:
            utils.clearScreen()

            print(
                "\n  Bibliotecas externas disponíveis para incluir ao seu novo projeto:\n"
            )

            # Lista as bibliotecas externas disponíveis.
            for n, i in enumerate(externalLibs):
                print("  X {:d}. {}".format(
                    n, i)) if n in newExecExternals else print(
                        "    {:d}. {}".format(n, i))

            print(
                "\n  Deseja incluir alguma? Isto é opcional. Depende do seu projeto."
            )
            print(
                "\n  Para incluir ou desfazer inclusão, informe o número referente à biblioteca."
            )
            print("  Quando estiver pronto, apenas pressione [ENTER].")

            # Recebe a biblioteca a ser adicionada ou descartada.
            libToAdd = input("\n  Índice da biblioteca: ")

            # Se nenhuma biblioteca for informada, pula esta etapa.
            if not libToAdd:
                break

            libToAdd = int(libToAdd)

            # Verifica se o valor informado está presente na lista.
            if not libToAdd in range(0, len(externalLibs)):
                raise ValueError()

            newExecExternals.remove(
                libToAdd
            ) if libToAdd in newExecExternals else newExecExternals.append(
                libToAdd)
        # Caso a opção informada seja inválida.
        except ValueError:
            input(
                "\n  Opção inválida! Pressione [ENTER] para tentar novamente.")

    # Ordena as bibliotecas externas.
    newExecExternals.sort()

    # Lista todos os executáveis existentes.
    executables = getExecs(cmakelistsFile)

    # Espera o usuário informar um nome para o executável.
    while True:
        try:
            utils.clearScreen()

            newExecName = str(
                input("\n  Informe o nome do novo executável: ")).strip()

            # Caso o nome informado seja inválido.
            if not newExecName or not newExecName.isidentifier():
                raise Exception("O nome informado é inválido!")

            # Caso o nome já existe.
            if newExecName in executables:
                raise Exception("Já existe um executável com este nome!")

            # Não pode permitir o nome "test" pois é reservado pelo CMake.
            if newExecName == "test":
                raise Exception("Este nome é reservado pelo CMake!")

            # Caso o nome seja muito extenso.
            if len(newExecName) >= 100:
                raise Exception("Este nome é muito extenso!")

            # Se chegou até aqui, o nome é válido.
            break
        except Exception as e:
            print("\n  {}".format(str(e)))
            input("\n  Pressione [ENTER] para tentar novamente...")

    utils.clearScreen()

    print("\n  Que título deseja dar ao executável?\n")
    print(
        "  Este título será usado apenas como comentário antes das entradas no arquivo CMakeLists.txt."
    )
    print(
        "  Se não informar nada, o título usado será igual ao nome do executável que definiu anteriormente.\n"
    )

    # Recebe um nome para o projeto.
    newExecTitle = str(input("  Título do projeto: ")).strip()

    # Se o nome informado estiver vazio, utiliza o nome da pasta do projeto.
    if not newExecTitle:
        newExecTitle = newExecName.capitalize()

    utils.clearScreen()

    # Monta o primeiro texto que deve ser adicionado ao CMakeLists.txt.
    firstTextToWrite = []

    firstTextToWrite.append("\n# {}\n".format(newExecTitle))
    firstTextToWrite.append("add_executable({}\n".format(newExecName))

    # Extrai apenas o nome da pasta do novo projeto.
    newExecFolder = newExecFolder.split(os.sep)[-1]

    # Inclui no primeiro texto os arquivos selecionados anteriormente.
    if selectedFiles:
        for i in selectedFiles:
            firstTextToWrite.append("\t{}/{}\n".format(newExecFolder,
                                                       availableFiles[i]))

        firstTextToWrite.append("\n")

    # Inclui as bibliotcas padrão selecionadas anteriormente.
    for lib in newExecLibs:
        for ext in ["cpp", "hpp"]:
            firstTextToWrite.append("\tcommon/{}.{}\n".format(libs[lib], ext))

    firstTextToWrite.append(")\n\n")
    firstTextToWrite.append("target_link_libraries({}\n".format(newExecName))
    firstTextToWrite.append("\t${ALL_LIBS}\n")

    # Inclui as bibliotecas externas.
    for lib in newExecExternals:
        firstTextToWrite.append("\t{}\n".format(externalLibs[lib]))

    firstTextToWrite.append(")\n\n")

    firstTextToWrite.append("# Xcode and Visual working directories\n")
    firstTextToWrite.append(
        "set_target_properties({} PROPERTIES XCODE_ATTRIBUTE_CONFIGURATION_BUILD_DIR \"${{CMAKE_CURRENT_SOURCE_DIR}}/{}/\")\n"
        .format(newExecName, newExecFolder))
    firstTextToWrite.append(
        "create_target_launcher({} WORKING_DIRECTORY \"${{CMAKE_CURRENT_SOURCE_DIR}}/{}/\")\n"
        .format(newExecName, newExecFolder))

    # Monta o segundo texto que deve ser adicionado ao CMakeLists.txt.
    secondTextToWrite = []

    secondTextToWrite.append("add_custom_command(\n")
    secondTextToWrite.append("   TARGET {} POST_BUILD\n".format(newExecName))
    secondTextToWrite.append(
        "   COMMAND ${{CMAKE_COMMAND}} -E copy \"${{CMAKE_CURRENT_BINARY_DIR}}/${{CMAKE_CFG_INTDIR}}/{}${{CMAKE_EXECUTABLE_SUFFIX}}\" \"${{CMAKE_CURRENT_SOURCE_DIR}}/{}/\"\n"
        .format(newExecName, newExecFolder))
    secondTextToWrite.append(")\n")

    # Recebe a linha em que o primeiro texto deve ser escrito.
    lineToAddFirstText = int(0)

    # Procura qual é a linha da última vez em que o comando "create_target_launcher()"
    # é chamado, para escrever o primeiro texto depois de tal linha.
    with open(cmakelistsFile, "r") as f:
        for n, i in enumerate(f):
            if "create_target_launcher(" in i:
                # É incrementado 1 e não 2 pois o índice das linhas na função open() começa em 0.
                lineToAddFirstText = n + 1

    # Flag de permissão de escrita do primeiro texto no arquivo.
    allowWriteFirstText = True

    # Caso não achou uma linha apropriada para adicionar o primeiro texto.
    if not lineToAddFirstText:
        while True:
            utils.clearScreen()

            # Exibe todo o texto que deve ser adicionado no CMakeLists.txt.
            print(
                "\n  Os comandos que devem ser escritos no CMakeLists.txt foram gerados com sucesso!"
            )
            print("\n  Primeira seção:")

            for i in firstTextToWrite:
                print(i)

            print("\n  Segunda seção:\n")

            for i in secondTextToWrite:
                print(i)

            # Espera por uma decisão do usuário.
            try:
                print(
                    "  O CMakeGL não encontrou um local apropriado para escrever a primeira seção."
                )
                print("  O que deseja fazer?\n")
                print("  [1] Incluir automaticamente mesmo assim.")
                print("  [2] Copiar o texto e incluir manualmente.\n")

                opt = int(input("  Sua opção: "))

                # Verifica se o valor informado está disponível.
                if not opt in [1, 2]:
                    raise ValueError()

                # Se o usuário quiser escrever o texto manualmente, não permite que o programa escreva posteriormente.
                if opt == 2:
                    allowWriteFirstText = False

                break
            except ValueError:
                input(
                    "\n  Opção inválida! Pressione [ENTER] para tentar novamente."
                )

    # Recebe a linha em que o segundo texto deve ser escrito.
    lineToAddSecondText = int(0)

    # Procura qual é a linha da última vez em que o comando "add_custom_command()"
    # é chamado, para escrever o segundo texto depois de tal função.
    with open(cmakelistsFile, "r") as f:
        for n, i in enumerate(f):
            if "add_custom_command(" in i:
                # É incrementado 4 e não 5 pois o índice das linhas na função open() começa em 0.
                lineToAddSecondText = n + 4

    # Flag de permissão de escrita do segundo texto no arquivo.
    allowWriteSecondText = True

    # Caso não achou uma linha apropriada para adicionar o segundo texto.
    if not lineToAddSecondText:
        while True:
            utils.clearScreen()

            # Exibe todo o texto que deve ser adicionado no CMakeLists.txt.
            print(
                "\n  Os comandos que devem ser escritos no CMakeLists.txt foram gerados com sucesso!"
            )
            print("\n  Primeira seção:")

            for i in firstTextToWrite:
                print(i)

            print("\n  Segunda seção:\n")

            for i in secondTextToWrite:
                print(i)

            # Espera por uma decisão do usuário.
            try:
                print(
                    "  O CMakeGL não encontrou um local apropriado para escrever a segunda seção."
                )
                print("  O que deseja fazer?\n")
                print("  [1] Incluir automaticamente mesmo assim.")
                print("  [2] Copiar o texto e incluir manualmente.\n")

                opt = int(input("  Sua opção: "))

                # Verifica se o valor informado está disponível.
                if not opt in [1, 2]:
                    raise ValueError()

                # Se o usuário quiser escrever o texto manualmente, não permite que o programa escreva, posteriormente.
                if opt == 2:
                    allowWriteSecondText = False

                break
            except ValueError:
                input(
                    "\n  Opção inválida! Pressione [ENTER] para tentar novamente."
                )

    # Inicia as operações finais.
    utils.clearScreen()

    print("\n  Tudo pronto!")

    print("\n  Executando as operações necessárias.")
    print("  Aguarde. Nenhuma ação é necessária.")

    # Faz o backup do arquivo CMakeLists.txt.
    print("\n  Fazendo backup do arquivo CMakeLists.txt...", end="")

    try:
        bkp = utils.backupFile(cmakelistsFile)

        print("\n  Backup realizado com sucesso!")
        print("  O backup está localizado em: {}".format(bkp))
    except IOError:
        print("\n  AVISO: Não foi possível realizar o backup!")

    # Escreve o primeiro texto no arquivo.
    if allowWriteFirstText:
        print("\n  Escrevendo a primeira seção no arquivo CMakeLists.txt...",
              end="")

        # Captura o conteúdo do arquivo e insere o primeiro texto na linha encontrada anteriormente.
        with open(cmakelistsFile, "r") as f:
            fileContent = f.readlines()

        fileContent[lineToAddFirstText:lineToAddFirstText] = firstTextToWrite

        fileContent = "".join(fileContent)

        # Tenta escrever o primeiro texto no arquivo.
        # Se der erro, finaliza o programa.
        while True:
            try:
                with open(cmakelistsFile, "w") as f:
                    f.write(fileContent)

                print("\n  Primeira seção escrita com sucesso!")

                break
            except Exception as e:
                print("\n  Houve um erro ao escrever a primeira seção:")
                print("\n  {}".format(str(e)))
                input("\n  Pressione [ENTER] para voltar ao menu principal...")

                return False

    # Escreve o segundo texto.
    if allowWriteSecondText:
        print("\n  Escrevendo a segunda seção no arquivo CMakeLists.txt...",
              end="")

        # Recebe a linha em que o segundo texto deve ser escrito.
        lineToAddSecondText = int(0)

        # Procura novamente qual é a linha da última vez em que o comando "add_custom_command()"
        # é chamado, para escrever o segundo texto depois de tal função.
        # É necessário verificar novamente já que o conteúdo
        # foi modificado pela inserção do primeiro texto.
        with open(cmakelistsFile, "r") as f:
            for n, i in enumerate(f):
                if "add_custom_command(" in i:
                    # É incrementado 4 e não 5 pois o índice das linhas na função open() começa em 0.
                    lineToAddSecondText = n + 4

        # Captura o conteúdo do arquivo e insere o segundo texto na linha encontrada anteriormente.
        with open(cmakelistsFile, "r") as f:
            fileContent = f.readlines()

        fileContent[
            lineToAddSecondText:lineToAddSecondText] = secondTextToWrite

        fileContent = "".join(fileContent)

        # Tenta escrever o segundo texto no arquivo.
        # Se der erro, finaliza o programa.
        while True:
            try:
                with open(cmakelistsFile, "w") as f:
                    f.write(fileContent)

                print("\n  Segunda seção escrita com sucesso!")

                break
            except Exception as e:
                print("\n  Houve um erro ao escrever a segunda seção:")
                print("\n  {}".format(str(e)))
                input("\n  Pressione [ENTER] para voltar ao menu principal...")

                return False

    # Constrói e compila o projeto.
    buildProj(cmakelistsFile)

    # Exibe uma última mensagem informando a finalização dos procedimentos.
    print("\n  Todas as operações pertinentes foram realizadas com êxito!")
    print(
        "  Confira no log acima se houve algum erro e, se necessário, execute esta etapa novamente."
    )

    input("\n  Pressione [ENTER] para voltar ao menu principal...")
Exemple #30
0
def main():
    utils.clearScreen()
    op = draw.showLoginMenu()
    if (op == 1):
        login() #REALIZA LOGIN
        while True:
            op = draw.showMainMenu()
            if (op == 1): #USUARIOS
                op = draw.showUserMenu()
                if (op == 1): #CADASTRO DE USUARIOS
                    callRegisterUser()
                    continue
                if (op == 2): #LISTAR USUARIOS
                    users.showUsers()
                    utils.pauseScreen()
                    continue
                if (op == 3): #DELETAR ARQUIVO DE USUARIOS
                    users.deleteUsersFile()
                    utils.pauseScreen()
                    continue
            if (op == 2): #CHAVES
                op = draw.showKeyMenu()
                if (op == 1): #GERAR CHAVES
                    if (keys.generateKeys() == True):
                        print("Chaves geradas com sucesso!")
                    else:
                        print("Chaves ja existentes!")
                    utils.pauseScreen()
                    continue
                if (op == 2): #SETAR BITSIZE RSA
                    keys.setBitsizeRSA()
                    utils.pauseScreen()
                    continue
                if (op == 3): #LISTAR CHAVES RSA DO USUARIO
                    keys.showKeys()
                    utils.pauseScreen()
                    continue
                if (op == 4): #DELETAR ARQUIVOS DAS CHAVES DO USUARIO
                    keys.deleteKeysFile()
                    utils.pauseScreen()
                    continue
                if (op == 5):
                    draw.showSelectUser()
                    keys.showOtherPublicKey()
                    utils.pauseScreen()
                    continue
            if (op == 3): #ARQUIVOS
                op = draw.showFileMenu()
                if (op == 1):
                    newfile = {}
                    newfile = draw.showSendFileMenu()
                    utils.updateSettingsToSendFile(newfile[globals.field_file_name],
                                                    newfile[globals.field_file_receiver])
                    files.createSendFile(newfile[globals.field_file_content])
                    utils.pauseScreen()
                    continue
            if (op == 0):
                break
    if (op == 2): #CADASTRAR USUARIO NO MOMENTO DE LOGIN LOGAR
        callRegisterUser()
        main()
    if (op == 3): #SAIR NA TELA DE LOGIN
        print("Programa finalizado!!!")