Esempio n. 1
0
def get_info():
    '''
    Get input from user for path, filename and password. Return values. 
    '''

    print('Please fill out the following prompts, which will be the info used '
          'to encrypt your PDF file.')
    path = pyip.inputStr('File path: ')
    filename = pyip.inputStr('File name: ')
    password = pyip.inputPassword(' Password: '******'\nValidating file path and whether specified filename exists...')
    try:
        os.chdir(path)
    except Exception as e1:
        print('\nERROR! Path is not valid. Exiting program.')
        print('Error: {}'.format(e1))
    try:
        os.stat(filename)
    except Exception as e2:
        print('\nERROR! Specified file is not valid. Exiting program.')
        print('Error: {}'.format(e2))
    else:
        print('Success! Path and filename OK.')

    return (path, filename, password)
Esempio n. 2
0
    def createTable(self):
        con = sqlite3.connect(self.name + '.db')
        con.row_factory = sqlite3.Row
        cur = con.cursor()

        print('1. CREATE FROM DB STUDIO LEVEL')
        print('2. CREATE BY SQL QUERY')
        userChoice = pyip.inputChoice(['1', '2'], ('(1/2)'))
        if userChoice == '1':
            tableName = pyip.inputStr('Table name:')
            # CREATING TABLE OBJECT
            table = Table(tableName)
            columnsAmount = pyip.inputInt('Columns amount:')
            for i in range(columnsAmount):
                columnName = pyip.inputStr('Column name: ')
                columnType = pyip.inputStr('Column type: ')
                # CREATING COLUMN OBJECT
                column = Column(columnName, columnType)
                # ADDING COLUMN OBJECT TO THE COLUMNS PROPERTY IN TABLE OBJECT
                table.columns.append(column)
        # ADDING TABLE TO THE TABLES PROPERTY IN DATABASE OBJECT
        self.tables.append(table)
        # CREATING SQL QUERY
        query = 'CREATE TABLE ' + table.name + ' (\n'
        for i in range(len(table.columns)):
            query += table.columns[i].name + table.columns[i].type + ',\n'
            # HEREEEE

            for i in range(len(table.columns)):
                print(table.columns[i].name, table.columns[i].type,
                      table.columns[i].value)
def mad_libs():
    """
    Create and read in text files
    and lets the user add their own text instead of words in constant.
    """
    input_file_path = Path("file.txt")
    output_file_path = Path("output_file.txt")
    new_text = []

    if not input_file_path.is_file():
        with open(input_file_path, "w") as input_file:
            input_file.write("The ADJECTIVE panda walked to the NOUN and then VERB. "
                             "A nearby NOUN was unaffected by these events.")

    with open(input_file_path, "r") as input_file, open(output_file_path, "w") as output_file:
        for line in input_file:
            slitted_sentence = re.findall(r"[\w']+|\.|\s", line)
            for word in slitted_sentence:
                if word in WORDS_TO_REPLACE:
                    input_word = pyip.inputStr(f"Please provide {word}:\n")
                    new_text.append(input_word)
                elif word[:len(word) - 1] in WORDS_TO_REPLACE:
                    input_word = pyip.inputStr(f"Please provide {word[:len(word) - 1]}:\n")
                    new_text.append(input_word + word[-1])
                else:
                    new_text.append(word)
        output_file.write("".join(new_text))

    print("".join(new_text))
def createDB():
    # clear the screen
    clear()
    print('CREATING DATABASE')
    print('1. CREATE FROM DB STUDIO LEVEL')
    print('2. CREATE MANUALLY BY SQL')
    print('3. EXIT')
    userInput = pyip.inputChoice(['1', '2', '3'], '(1/2/3):')
    # IF USER PRESS 3 EXIT
    if userInput == '3':
        return
# CREATING DB FROM THE DB STUDIO LEVEL
    elif userInput == '1':
        ifExists = True
        # getting db name and checking if such DB exists
        while ifExists:
            DBName = pyip.inputStr('Provide name of the DataBase:')
            path = Path.cwd() / DBName
            if path.exists():
                print('There is DB with this name already!')
            else:
                ifExists = False
# CREATING DB BY SQL QUERY
    else:
        query = pyip.inputStr('Provide SQL query:',
                              allowRegexes=(r'CREATE DATABASE (/w)+;'),
                              blockRegexes=(r'.*'),
                              limit=3)
        DBName = re.sub('CREATE DATABASE ', '', query)
        DBName = re.sub(';', '', DBName)
    DB = DataBase(DBName)
def multplication_quiz(questions):
    """
    Poses a number of multiplication problems to the user.

    Args:
        questions (int): Number of questions to pose.
    """
    correct_anwsers = 0

    for question_number in range(1, questions):
        # Pick two random numbers
        num1 = random.randint(0, 9)
        num2 = random.randint(0, 9)
        prompt = f'Question #{question_number}: {num1} x {num2} = '

        try:
            # Right answers are handled by allowRegexes.
            # Wrong answers are handled by blockRegexes, with a custom message.
            pyip.inputStr(prompt,
                          allowRegexes=[f'^{num1 * num2}$'],
                          blockRegexes=[('.*', 'Incorrect')],
                          timeout=8,
                          limit=3)
        except pyip.TimeoutException:
            print('Out of Time!')
        except pyip.RetryLimitException:
            print('Out of tries!')
        else:
            # This block runs if no exceptions were raised in the try block.
            print('Correct!')
            correct_anwsers += 1
            # Brief pause to let the user read the message
            time.sleep(1)
    print(f'Your Score is {correct_anwsers} / {questions}')
Esempio n. 6
0
    def create_user_config(self) -> None:
        """
        Creates a user config file
        """
        
        print("Seems like you're information is not on file. Let's set up")
        # User input their name
        name = pyip.inputStr("Please enter your name:\n")
        while True:
            # User input their username which is also used as table name in mysql
            user = pyip.inputStr("Please enter a username:\n").lower()
            # Remove spaces in the username
            user = re.compile(r'\s*').sub('',user)
            
            # If the table does not exist
            if self.check_sql_table(user):
                # Create the table
                self.create_sql_table(user)
                break
            # If the table exist
            print("Username is unavailable. Please try again")
        
        pswd = password.confirm_password()
        email = self.validate_email()

        self.write_user_config(name, user, pswd)
def delete_information():
    """Lets the user select if all content or a single entry shall be deleted. Returns None.
    Either deletes the complete file or asks for input to identify the entry to be deleted.
    """
    entry = pyip.inputMenu(['delete all content', 'delete a single entry',
                           ],
                           numbered=True)

    if entry == 'delete all content':
        try:
            file = open('AddressBook.csv', 'w', newline='')
        except IOError:
            print('File not accessible.')
        file.close()

    if entry == 'delete a single entry':
        list_of_entries = []
        try:
            file = open("AddressBook.csv", "r", newline='')
        except IOError:
            print('File not accessible.')
        filereader = csv.DictReader(file)
        for row in filereader:
            list_of_entries.append(row)
        file.close()
        name = pyip.inputStr(PHRASE.format('first name'),
                         blockRegexes=[(r'\d+',
                                        "Names should contain only letters.")])
        surname = pyip.inputStr(PHRASE.format('surname'),
                            blockRegexes=[(r'\d+',
                                          "Names should contain only letters.")])
        delete_entry(list_of_entries, name, surname)
def single_entry(filereader, updating=False):
    """Prints or returns an entry. Use updating flag to switch between printing and returning.

    :param filereader: a filereader object from which an entry should be printed or returned.
    :type filereader: filereader object
    :param updating: flag that switches between returning and print. Default = False = printing.
    :type updating: bool
    :returns: entry that matches with the name and surname asked for.
    :rtype: dict
    """
    name = pyip.inputStr(PHRASE.format('first name'),
                         blockRegexes=[(r'\d+',
                                        "Names should contain only letters.")])
    surname = pyip.inputStr(PHRASE.format('surname'),
                            blockRegexes=[(r'\d+',
                                          "Names should contain only letters.")])
    list1 = [name.lower(), surname.lower()]
    count = 0
    for row in filereader:

        if all(any(entered == value.lower() for value in list(row.values())) for entered in list1):
            print('found entry.')
            if not updating:
                print(row)
                count += 1
            if updating:
                count += 1
                return row
    if count == 0:
        print("Entry not found.")
Esempio n. 9
0
def fill_in_gaps():
    folder_path_prompt = 'Enter the absolute filepath of the desired folder to copy from:\n'
    folder_path = pyip.inputStr(prompt=folder_path_prompt)

    prefix_prompt = 'Enter the prefix of the files that you want to check:\n'
    prefix = pyip.inputStr(prompt=prefix_prompt)

    file_regex = re.compile(rf'^({prefix})(\d+)(.*?)$')
    matching_file_list = sorted([file for file in os.listdir(folder_path) if file_regex.match(file)])

    if len(matching_file_list) == 0:
        return

    start_value = int(file_regex.search(matching_file_list[0]).group(2))
    count = start_value
    max_length = len(file_regex.search(matching_file_list[-1]).group(2))

    for file in matching_file_list:
        mo = file_regex.search(file)
        file_num = int(mo.group(2))

        if file_num != count:
            new_file_name = prefix + '0'*(max_length-len(str(file_num))) + str(count) + mo.group(3)
            shutil.move(os.path.join(folder_path, file), os.path.join(folder_path, new_file_name))
        count += 1
Esempio n. 10
0
def urlCreate():  # Setting up the URL(s)
    global vehicleBrand, model, url, pageCounter
    vehicleBrand = pyip.inputStr('Marka: ', limit=3)
    model = pyip.inputStr('Model: ')
    vehicleBrand = vehicleBrand.lower()
    model = model.lower()
    url = str('https://www.otomoto.pl/osobowe/' + vehicleBrand + '/' + model +
              '/')
Esempio n. 11
0
def getNames():
    '''
    to get each player name to be used in the main game
    '''
    a = pyip.inputStr(prompt='Player-1 enter your name: ', blockRegexes=[r'[0-9]|[!@#~$%^&*()_+\]\[\'\":/><?]'],
                      default='Enter a string not a digit!')
    b = pyip.inputStr(prompt='Player-2 enter your name: ', blockRegexes=[r'[0-9]|[!@#~$%^&*()_+\]\[\'\":/><?]'],
                      default='Enter a string not a digit!')
    return a, b
Esempio n. 12
0
def create_user_data():
    username = pyip.inputStr(prompt='Username: '******'First Name: ')
    last_name = pyip.inputStr(prompt='Last Name: ')
    age = pyip.inputInt(prompt='Age: ', min=1, max=99)
    email = pyip.inputEmail(prompt='Email: ', )
    country = pyip.inputStr(prompt='Country: ')
    join_date = get_date()
    return username, first_name, last_name, age, email, country, join_date
Esempio n. 13
0
def decrypt_pdf():
    """Use words list from dictionary_file to decrypt pdf file."""
    path_to_dict = Path(inputStr("Provide absolute path to dictionary file: "))
    path_to_pdf = Path(inputStr("Provide absolute path to encrypted pdf file: "))
    with open(path_to_dict, 'rt') as my_file:
        dictionary = my_file.read()
    pdf_reader = PyPDF4.PdfFileReader(open(path_to_pdf, 'rb'))
    for word in dictionary.split():
        if pdf_reader.decrypt(word) == 1:
            print(f"Password found! It's: {word}")
            break
        elif pdf_reader.decrypt(word.lower()) == 1:
            print(f"Password found! It's: {word.lower()}")
            break
Esempio n. 14
0
def copy_chosen_extension(file_type):
    """Find in a tree, files with given extension and copy to chosen folder."""
    data_folder = Path(
        inputStr("Provide absolute path to tree parent folder: "))
    destination_folder = Path(
        inputStr("Provide absolute path to destination folder: "))
    os.makedirs(destination_folder, exist_ok=True)
    files_in_folder = data_folder.rglob(f'*.{file_type}')
    copied_files = []
    if not files_in_folder:
        print("No files with given extension in chosen folder")
        return
    for file in files_in_folder:
        shutil.copy(file, destination_folder)
        copied_files.append(file)
Esempio n. 15
0
def releasequestions(
):  # Ask the user a series of questions then store that data to create a "Release" file later.
    global repo_origin, repo_label, repo_suite, repo_version, repo_codename, repo_architecture, repo_components, repo_description

    repo_origin = pyip.inputStr("Repo Name: ")
    #repo_label = pyip.inputStr("Label:* ", blank=True)
    #if repo_label == "":
    #    repo_label = repo_origin
    repo_label = repo_origin
    repo_suite = config.RepoSuite
    repo_version = config.RepoVersion
    repo_codename = config.RepoCodeName
    repo_architecture = config.RepoArchitecture
    repo_components = config.RepoComponents
    repo_description = pyip.inputStr("Description: ")
def get_app_info():
    try:
        print('------------------------------------')
        print('How do you want to name your app?')
        name = pyip.inputStr(limit=2).replace(' ', '_')
        print('------------------------------------')
        print('Do you need a database?')
        input_database = pyip.inputMenu(['yes', 'no'], limit=2, numbered=True)
        models = list()
        if input_database == 'yes':
            database = True
            models_bool = True
            while models_bool:
                print('Do you want to add a database table?')
                input_model = pyip.inputMenu(['yes', 'no'],
                                             limit=2,
                                             numbered=True)
                if input_model == 'yes':
                    model_name = pyip.inputStr('Tablename: ').replace(
                        ' ', '_').capitalize()
                    models.append(model_name)
                else:
                    models_bool = False
        else:
            database = False

        blueprint_names = list()
        blueprints_bool = True
        blueprints = False
        print('------------------------------------')
        while blueprints_bool:
            print('Do you want to add a blueprint?')
            blueprint = pyip.inputMenu(['yes', 'no'], limit=2, numbered=True)
            if blueprint == 'yes':
                blueprint_name = pyip.inputStr('Blueprintname: ').replace(
                    ' ', '_').lower()
                blueprint_names.append(blueprint_name)
                blueprints = True
            else:
                blueprints_bool = False

        app = AppManager(name, database, models, blueprints, blueprint_names)

    except pyip.RetryLimitException as e:
        print('ERROR: You exceeded the input limit.')
        return sys.exit()

    return app
Esempio n. 17
0
def addacc(): #add acc
    Account_id = None
    UserID = input('New UserID/email:') #can be left blank
    pw_option = pyip.inputYesNo('Generate random password?')
    if pw_option == 'yes':
        Pass = passwordgenerator()
    else:
        Pass = pyip.inputStr('Password:'******'Remarks:')
    displaypurpose()
    items = list(cursor.execute('''SELECT * from Purpose''').fetchall())
    key_list = [str(item[0]) for item in items ]
    if len(key_list) >= 2:
        print('Choose the following keys:')
        choose_key = pyip.inputMenu(key_list,numbered=True) #choose the key of the item
    else:
        choose_key = key_list[0] #1st item



    
    db.execute('''INSERT INTO Accounts('Account_id','UserID','Pass','Remarks','PurposeID') VALUES (?,?,?,?,?)''',\
               (Account_id,UserID,Pass,Remarks.title(),choose_key))
    if Remarks != '':
        Remarks = Remarks.title()
    acctable
    db.commit()
    print('Finish adding')
Esempio n. 18
0
    def existing_user(self) -> None:
        """
        If the user already have an existing user
        """

        name = pyip.inputStr("Enter your name:\n")
        user = pyip.inputStr("Enter your username:\n").lower()
        while self.check_sql_table(user):
            user = pyip.inputStr("Username Does not exist. Please enter it again.\n").lower()
            user = re.compile(r'\s*').sub('',user)
        
        pswd = password.confirm_password()
        email = self.validate_email()
        

        self.write_user_config(name, user, pswd)
Esempio n. 19
0
def main():
    username = pyip.inputStr('Amazon Username: '******'Amazon Password: '******'*')
    passwordCheck = pyip.inputPassword('Re-enter Amazon Password: '******'*')

    if password != passwordCheck:
        print('Passwords did not match. Please try again.')
        exit(0)

    browser = webdriver.Firefox()
    browser.get(
        'https://www.amazon.com/gp/offer-listing/B08HH5WF97/ref=dp_olp_unknown_mbc'
    )

    while True:
        try:
            priceElem = browser.find_element_by_css_selector(
                'span.a-size-large')
            buttonElem = browser.find_element_by_css_selector(
                '.a-button-input')
        except:
            logging.info('No current offers available')

        if convertToNum(priceElem.text) < 800 and isNewCondition(browser):
            buttonElem.click()
            logging.info('Adding to cart')
            if not testing:
                signInandPlaceOrder(browser, username, password)
            browser.quit()
            break

        time.sleep(15)
        logging.info('Refreshing')
        browser.refresh()
Esempio n. 20
0
def edit_sheet(chosen_file):  #edit sheets
    option = 'yes'
    while option == 'yes':  #choose what sheet
        openbook = openpyxl.load_workbook(chosen_file)
        sheets = openbook.sheetnames
        chosen_sheet = None

        if len(sheets) >= 2:
            chosen_sheet = pyip.inputMenu(sheets, numbered=True)
        elif len(sheets) == 1:
            chosen_sheet = sheets[0]
        else:
            print('N/A')
        if chosen_sheet != None:
            chosen_sheet_obj = openbook[
                chosen_sheet]  #change it into sheet obj
            view_sheet(chosen_file, chosen_sheet)
            chosen_row = pyip.inputInt('Choose a row:')
            chosen_column = pyip.inputInt('Choose a column:')
            new_value = pyip.inputStr('New value:')

            chosen_sheet_obj.cell(\
                row = chosen_row,column = chosen_column ).value = new_value

            openbook.save(chosen_file)
            option = pyip.inputYesNo('Anymore to edit?')
Esempio n. 21
0
    def login(self):
        try:
            username_input = self.driver.find_element_by_id('username')
            password_input = self.driver.find_element_by_id('password')
            login_input = self.driver.find_element_by_xpath(
                '/html/body/div/main/div[2]/div[1]/form/div[3]/button')
        except Exception as exc:
            print('%s' % (exc))

        username = pyinp.inputStr(prompt='Username: '******'Password: '******'error-for-username')
            error2 = self.driver.find_element_by_id('error-for-password')
            if error1.is_displayed():
                print('Error for username')
            elif error2.is_displayed():
                print('Error for password')
            self.driver.find_element_by_id('username').clear()
            self.login()
        except:
            print('Loged!')
Esempio n. 22
0
def main():

    mailAddress = pyinputplus.inputEmail("Enter email address: \n")
    pw = pyinputplus.inputPassword("Enter password for sending the mail: \n",
                                   timeout=10)
    mailMessage = pyinputplus.inputStr("Enter message to send: \n")
    send_mail(mailAddress, pw, mailMessage)
    def encrypt(cls, method='AES'):
        plaintext = pyip.inputStr('enter data for encryption :  ')
        plaintext = str.encode(plaintext)

        key = stdiomask.getpass()
        key = str.encode(key)

        if (method == 'AES'):
            if (len(key) < 16):
                key = key + str.encode((16 - len(key)) * 'a')
            elif (len(key) > 16):
                key = key[:16]
            cipher = AES.new(key, AES.MODE_EAX)

            nonce = cipher.nonce
            ciphertext, tag = cipher.encrypt_and_digest(plaintext)

            print('nonce: \n' + str(nonce),
                  '\nciphertext: \n' + str(ciphertext), '\ntag: \n' + str(tag))
            return (nonce, ciphertext, tag)

        elif (method == 'Salsa20'):
            if (len(key) < 32):
                key = key + str.encode((32 - len(key)) * 'a')
            elif (len(key) > 32):
                key = key[:32]
            cipher = Salsa20.new(key=key)
            ciphertext = cipher.nonce + cipher.encrypt(plaintext)
            print('ciphertext: \n' + str(ciphertext))
            return ciphertext
Esempio n. 24
0
    def tcp_port_scanner(self):
        ascii_banner = pyfiglet.figlet_format("PORT SCANNER")
        print(ascii_banner)

        target = pyip.inputStr('host name: ')

        # Add Banner
        print("-" * 50)
        print("Scanning Target: " + target)
        print("Scanning started at:" + str(datetime.now()))
        print("-" * 50)

        try:

            # will scan ports between 1 to 65,535
            for port in tqdm(range(1, 65535)):
                s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                socket.setdefaulttimeout(1)

                # returns an error indicator
                result = s.connect_ex((target, port))
                if result == 0:
                    print("\nPort {} is open".format(port))
                s.close()

        except KeyboardInterrupt:
            print("\n Exitting Program !!!!")
        except socket.gaierror:
            print("\n Hostname Could Not Be Resolved !!!!")
        except socket.error:
            print("\n Server not responding !!!!")

        return
Esempio n. 25
0
def search(word):
    if not words_list():  # ie no words in the dictionary
        print("Dictionary is empty :(")
        return

    # get all words and meanings
    words = {}
    f = open("C:\\Users\\abukh\\MyPythonScripts\\dictionary.txt")
    for w in f:
        if w == '\n':
            continue
        w = w.split(' ')
        words[w[0].lower()] = " ".join(w[1:])
    f.close()

    # display word if it exists, else offer to add it to the dictionary
    if word in words.keys():
        print(f'\n{word.capitalize()}\n   -{words[word]}')
    else:
        add_word = pyip.inputChoice(
            ['y', 'n'],
            "No such word found in your dictionary, wanna add it (y/n)? ")
        if add_word == 'y':
            print(f"\nWord: {word.capitalize()}")
            meaning = pyip.inputStr(f"Enter {word}'s meaning: ")
            add(word.lower(), meaning)
            print("Word added!")
Esempio n. 26
0
    def valid_user(self):
        self.screen.display()
        if not self.db.check(self.__id):
            try:
                print(f"[INFO] {self.__id} is not registered yet.", end=' ')
                ans = pyip.inputYesNo('Do you want to register? (y/n) ',
                                      limit=3,
                                      yesVal='y',
                                      noVal='n')
                if ans == 'y':
                    name = pyip.inputStr('Enter a name: ', limit=3)
                    money = pyip.inputInt('Initial money (default 0): ',
                                          limit=3,
                                          default=None)

                    response = self.db.register(self.__id, name, money)
                    if response:
                        self.add(money)
                        print(
                            f'[INFO] User: (id:{self.__id}, name:{name}, money:{money}$) was succesfully registered in the Database.'
                        )
                    else:
                        print('[ERROR] Something was wrong with the register.')
                        print('Thanks for using the script!')
                        sys.exit()

                else:
                    sys.exit()
            except pyip.RetryLimitException:
                print(f'[ERROR] Limit of attempts exceeded.')
Esempio n. 27
0
def selectiveCopier(filepath, fileType):
    p = Path(filepath)
    c = Path(p / 'Copy')
    #Create a new Dictonary
    while True:
        try:
            #If succesfull create one and break the Loop
            os.makedirs(c)
            break
        #Folder exists alredy
        except:
            #Should be a new one created?
            prompt = 'Copy Folder exists already\nShould a new Copy be created (yes/no)\n'
            response = pyinputplus.inputYesNo(prompt)
            response = response.lower()
            #Create a new folder Path with New name, os.makedits above creates new one or another erros leads back here
            if response == 'yes':
                prompt2 = 'Name?\n'
                newName = str(pyinputplus.inputStr(prompt2))
                c = Path(p / newName)
            #Close Program
            else:
                os._exit(1)
    #Walks through entire Path
    for filename in p.rglob('*.jpg'):
        try:
            #Copies of possible
            shutil.copy(filename,c)
        except:
            #Files can't exist twice
            print(f'"{filename}" is already Backed up')
Esempio n. 28
0
def run_setup():
    # for persistent data; saves and retrieves user credentials
    # Will prompt user for credentials and for servers running call manager service
    # enter servers seperated by comma "," no spaces e.g. 10.10.10.1,10.10.10.2,10.10.10.3

    st_setup = pyip.inputYesNo('\nEnter setup ? (yes or no): ')
    setup_var = shelve.open('cli_var')

    if st_setup == 'yes':
        usern = input('username: '******'password: '******'s seperated by comma ',' :")
        servers = servers.split(',')
        setup_var['cli_user'] = usern
        setup_var['cli_pw'] = pphrase
        setup_var['servers'] = servers
        setup_var.close()

    else:
        if ('cli_user' in setup_var) and ('cli_pw' in setup_var):
            print('Using saved credentials')
            usern = setup_var['cli_user']
            pphrase = setup_var['cli_pw']
            servers = setup_var['servers']
            setup_var.close()

    return usern, pphrase, servers
Esempio n. 29
0
def create_fighter(name=None):
    while True:
        # если параметров не было, то попросить ввести имя
        if name == None:
            name = pyip.inputStr(
                "Введите имя: ",
                blockRegexes=[r'[@#$%^&*()_+!"№;:?*-=.,><"]$'])
        # если такое имя есть...
        if isExist(name):
            # то предложить создать бойца с другим именем
            response = print_yn(
                "Боец с таким именем уже существует! Хотите ввести другое? y/n\n"
            )
            if (response == "yes"):
                name = None
                continue
            else:
                return
        # если нет такого имени, то продолжаем
        else:
            break

    # выбрать класс
    ans_class = pyip.inputInt("Выберите класс: 1 - Воин, 2 - Маг\n",
                              min=1,
                              max=2)
    new_fighter = None
    if (ans_class == 1): new_fighter = Warrior(name)
    else: new_fighter = Mage(name)
    print_g("Боец создан!")
    return new_fighter
Esempio n. 30
0
 def pause(self):
     '''
     this is just a randomly made method to pasue the game
     '''
     play = pyip.inputStr(prompt='< Press ENTER to continue > ', blank=True,
                          blockRegexes=[(r'[a-zA-Z0-9]', 'ONLY ENTER!')])
     return play