コード例 #1
0
ファイル: models.py プロジェクト: hwyfour/hangman
    def new_game(cls, user, attempts = 6):
        """Create a new Game."""

        # Get a random word from our dictionary, brought to you by our imported words.py
        word = get_word()

        # Create the Game, assigning all blanks to the public_word
        game = Game()
        game.private_word = word
        game.public_word = '_' * len(word)
        game.attempts_allowed = attempts
        game.attempts_remaining = attempts
        game.guesses = []
        game.guesses_set = set()
        game.game_over = False
        game.cancelled = False
        game.won = False
        game.user = user

        # Get a unique id for this game
        game_id = Game.allocate_ids(size = 1, parent = user)[0]
        # So we can link this Game as a descendant to this User for easy querying
        game.key = ndb.Key(Game, game_id, parent = user)
        # Store the new Game
        game.put()

        return game
コード例 #2
0
def play_hangman():
    print('Starting a game of Hangman...')
    false_attempts = get_num_attempt()
    minWordLength = get_min_word_length()

    # Randomly selecting a word
    print('Selecting a word...')
    word = get_word(minWordLength)
    print()

    # setting the game state parameter
    idxs = [letters not in ascii_lowercase for letters in word]
    remaining_letters = set(ascii_lowercase)
    wrong_letters = []
    word_resolved = False

    # Main Game loop
    while false_attempts > 0 and not word_resolved:
        """ Printing the current Game state"""
        print('word : {}'.format(display_word(word, idxs)))
        print('remaining attempts : {}'.format(false_attempts))
        print('previous Guesses : {0}'.format(' '.join(wrong_letters)))

        # get Player next guess
        next_letter = get_next_letter(remaining_letters)

        # check if guessed letter is n the word or not
        if next_letter in word:
            # guessed correctly
            print('{} is in the word'.format(next_letter))

            # Reveal matching letters
            for i in range(len(word)):
                if next_letter == word[i]:
                    idxs[i] = True
        else:
            # Guessed incorrectly
            print('{} is not in word'.format(next_letter))
            # Decreases no of remaining attempts and append guess to wrong letters
            false_attempts -= 1
            wrong_letters.append(next_letter)

        # check if word is properly resolved or not
        if False not in idxs:
            word_resolved = True
        print()

    # the game is over, Reveal the word
    print('word : {}'.format(word))

    # Result
    if word_resolved:
        print('Congratulations!!! You Won...')
    else:
        print('Better Luck Next Time...')

    # User want to try again or not
    try_again = input('You want to try again [Y / y] : ')
    return try_again.lower() == 'y'
コード例 #3
0
def play_again():
    while True:
        choice = input("\nPlay again? y/n: ")

        if choice == 'y' or choice == 'Y':
            play_hangman(words.get_word())
        elif choice == 'n' or choice == 'N':
            break
        elif choice != 'y' or choice != 'Y' or choice != 'n' or choice != 'N':
            continue
コード例 #4
0
ファイル: hangmanUtils.py プロジェクト: San7ay/hangman
def play_hangman():
    print('Welcome to hangman game!! Try not to be hanged')
    level = input(
        'Select the required difficulty level\n(1) EASY \n(2) MEDIUM\n(3) DIFFICULT\n'
    )

    word = words.get_word(level)
    # print(word)              uncomment to know the word selected for testing
    """Initially set 'False' to all the letter in the word ....list show be same size as word length"""
    index = [letter not in string.ascii_lowercase for letter in word]
    remaining_letters = set(string.ascii_lowercase)
    wrong_letters = []
    word_solved = False
    number_of_attempts = len(
        word)  # choose num of attempts as num of letter in word

    while number_of_attempts > 0 and not word_solved:
        print('Word: {0}'.format(get_display_word(word, index)))
        print('Attempts remaining: {0}'.format(number_of_attempts))

        next_letter = get_next_letter(number_of_attempts, remaining_letters)

        if next_letter in word:
            print('{0} is in the word'.format(next_letter))
            for i in range(len(word)):
                if word[i] == next_letter:
                    index[i] = True
        else:
            print('{0} is NOT in the word'.format(next_letter))

        number_of_attempts -= 1
        wrong_letters.append(next_letter)

        if False not in index:
            word_solved = True
        print()

    print('"{0}" is the word'.format(word))

    if word_solved:
        print('Congrats!! you won')
    else:
        print('Better luck next time')

    tryagain = input('would you like to play again? [y/n]')
    return tryagain.lower() == 'y'
コード例 #5
0
def assess_tokens(tokens, allow_fetch=True):
    '''Read and analyze a list of tokens. For each discovered work,
    entire word assertions exist.

    return a tuple of tokens with a word ident object.
    '''
    print 'Assessing:'

    send_json(type='assess', action='start', tokens=tokens)
    tree = nltk.chunk.ne_chunk(tokens)

    res = []
    for word, typeof in tokens:
        item = (
            word,
            typeof,
            type_map.get(typeof, '[NO TYPE]'),
        )
        res.append(item)

    send_json(type='assess', action='complete', result=res, tokens=tokens)
    iter_print(tokens)

    res = ()

    for word, wtype in tokens:
        # thin_structure_words['words'][3] == tokens
        ident = assess_word_token(word, wtype, tokens, allow_fetch=allow_fetch)

        wdd = words.get_word(word)
        wdd['meaning_result'] = bind_meaning(wdd, wtype)
        res = res + ((word, wtype, ident, wdd), )

        send_json(
            type='assess',
            action='word',
            word=wdd,
            word_type=wtype,
            tokens=tokens,
            ident=ident,
        )
        # print_edges(ident)
    return dict(tree=tree, ident=ident, words=res, original=tokens)
コード例 #6
0
def main():
    global username
    global city
    global voice
    music = None
    music_list = []
    if username == "":
        Speak("Hello. I'm your virtual assistant. What's your name?")
        username = input(
            "Hello I'm your virtual assistant What's your name?\n")
        data = json.load(open('Data\\user.json', ))
        data["username"] = username
        with open("Data\\user.json", "w") as f:
            f.write(json.dumps(data))
    if city == "":
        while True:
            Speak("Please enter your city")
            city = input("Please Enter Your City :\n")
            geolocator = Nominatim(user_agent='myapplication')
            location = geolocator.geocode(city)
            if location != None:
                break
        data = json.load(open('Data\\user.json', ))
        data["city"] = city
        with open("Data\\user.json", "w") as f:
            f.write(json.dumps(data))

    if not path.exists('Utils\\ffmpeg.exe'):
        print(
            "Please Make Sure To Download The Utils (FFMPEG.exe was not found)"
        )
        Speak(
            "Please Make Sure To Download The Utils (F F M P E G dot exe was not found)"
        )
        sleep(10)
        return False

    Speak(f"Good {welcome_mesage()} {username}")
    Speak(
        f"it is {int(strftime('%I'))} {int(strftime('%M'))} {strftime('%p')}")

    while True:

        try:
            calc = False
            with sr.Microphone() as source2:
                print("Adjusting Audio")
                r.adjust_for_ambient_noise(source2, duration=0.2)
                print("Listening")
                audio2 = r.listen(source2)
                print("Processing The Data ")
                MyText = r.recognize_google(audio2)
                MyText = MyText.lower()
                print("You said :" + MyText)

                # Replace numbers for Calculator
                MyText = replace_theTexting_by_num(MyText)
                for i in MyText:
                    if i in numbers:
                        calc = True

                if calc == True:
                    MyText = replace_expresions(MyText)

                # Say Hello
                if "hello" in MyText:
                    Speak("Hello to you too!")

                if "+" in MyText or "-" in MyText or "*" in MyText or "/" in MyText or "sqrt" in MyText:
                    try:
                        result = eval(MyText)
                        Speak(f"The answer is {result}")
                        print(f"The answer is {result}")

                    except:
                        Speak("What was That ?")

                elif "weather" in MyText:
                    Speak("Checking Weather")
                    Speak(
                        f"The weather in {city} is {weather_message()[0]}  degrees ,  and {weather_message()[1]}"
                    )

                elif "date" in MyText and not "update" in MyText:
                    Speak("Today is " + str(strftime('%A')) +
                          str(int(strftime('%d'))) + str(strftime('%B')) +
                          str(strftime('%Y')))

                elif "azan" in MyText or "pray" in MyText:
                    Speak(get_prayer(city))

                elif "time" in MyText:
                    Speak(
                        f"it is {int(strftime('%I'))} {int(strftime('%M'))} {strftime('%p')}"
                    )

                elif "change" in MyText and "name" in MyText:
                    Speak("What's your name?")
                    username = input("What's your name?\n")
                    data = json.load(open('Data\\user.json', ))
                    data["username"] = username
                    with open("Data\\user.json", "w") as f:
                        f.write(json.dumps(data))

                elif "change" in MyText and "city" in MyText:
                    while True:
                        Speak("Please enter your new city")
                        city = input("Please Enter Your New City :\n")
                        geolocator = Nominatim(user_agent='myapplication')
                        location = geolocator.geocode(city)
                        if location != None:
                            break
                    data = json.load(open('Data\\user.json', ))
                    data["city"] = city
                    with open("Data\\user.json", "w") as f:
                        f.write(json.dumps(data))

                # Voice Changing
                elif "change" in MyText and "voice" in MyText:
                    for a in range(len(v)):
                        engine.setProperty('voice', (v[a]))
                        Speak(f"For this voice press {a}")
                    while True:
                        c = input("Please Choose (0, 1) :")
                        if c in ("0", "1"):
                            c = int(c)
                            break
                    data = json.load(open('Data\\user.json', ))
                    data["voice"] = c
                    with open("Data\\user.json", "w") as f:
                        f.write(json.dumps(data))

                    voices = engine.getProperty('voices')

                    engine.setProperty('voice', v[int(c)])

                # Notes
                elif "note" in MyText:
                    if "take" in MyText:
                        with open("Data\\notes.txt", "a") as f:
                            Speak("Please Type Your Notes")
                            notes = input("Please Type Your Notes :\n")
                            f.write(notes + "\n")
                    elif "delete" in MyText or "remove" in MyText:
                        Speak("Your Notes Will Be Deleted. Are You Sure")
                        notes = input("Are you sure (Y/N):\n")
                        if notes.lower() == "y":
                            with open("Data\\notes.txt", "w") as f:
                                f.write("")
                    else:
                        with open("Data\\notes.txt", "r") as f:
                            Speak(f.read())

                # Open Programmes
                elif "open" in MyText:
                    MyText = MyText.replace("open ", "")
                    x = openApp(MyText)
                    if not x:
                        Speak("Here's some results from the internet")
                    else:
                        Speak(f"opening {str(MyText)}")

                # Google Search
                elif "google" in MyText:
                    search = MyText.replace("google ", "")
                    wb.open_new_tab(
                        f'https://www.google.com/search?q={search}')

                elif "what is" in MyText or "what's" in MyText:
                    search = MyText.replace("what is ", "")
                    try:
                        print(wikipedia.summary(search))
                        Speak("According to wikipedia " +
                              str(wikipedia.summary(search, sentences=4)))
                    except:
                        search = MyText.replace("what is ", "")
                        wb.open_new_tab(
                            f'https://www.google.com/search?q={search}')

                elif "who is" in MyText:
                    search = MyText.replace("who is ", "")
                    try:
                        print(wikipedia.summary(search))
                        Speak("According to wikipedia " +
                              str(wikipedia.summary(search, sentences=4)))
                    except:
                        search = MyText.replace("who is ", "")
                        wb.open_new_tab(
                            f'https://www.google.com/search?q={search}')

                # Download From Youtube
                elif "download" in MyText:
                    if 'music' in MyText:
                        url = speakInput(
                            "Please write down the name of the song you want to download :"
                        )
                        youtube_downloader.youtube_download(url, "music")
                    elif "youtube" in MyText:
                        url = speakInput(
                            "Please type the name of the video you want to download :"
                        )
                        youtube_downloader.youtube_download(url, "youtube")

                elif "convert" in MyText:
                    fileConverter.convertFile()

                # Music Player
                elif "music" in MyText:
                    if "play" in MyText:
                        artist = MyText.replace("play music ", "")
                        if artist == "play music":
                            artist = get_word("artist")

                        Speak(f"Playing {artist} Music")
                        music, music_list = music_player(artist, music)

                    elif "pause" in MyText or "stop" in MyText or "continue" in MyText:
                        pause_music(music)

                    elif "next" in MyText:
                        if music == None:
                            artist = get_word("artist") + " music"
                            music, music_list = music_player(artist, music)
                        else:
                            Speak("Playing next music")
                            music = next_music(music, music_list)

                # Brightness Control
                elif "brightness" in MyText:
                    old = sbc.get_brightness()
                    if "increase" in MyText or "raise" in MyText:
                        sbc.set_brightness(old + 25)
                        speakPrint(f"increasing brightness")
                    elif "max" in MyText:
                        sbc.set_brightness(100)
                        speakPrint(f"maximum brightness")
                    elif "decrease" in MyText or "lower" in MyText:
                        speakPrint(f"decreasing brightness")
                        sbc.set_brightness(old - 25)
                    elif "min" in MyText:
                        speakPrint(f"Mnimun brightness")
                        sbc.set_brightness(0)
                    else:
                        speakPrint(f"Current brightness is {old}")

                elif "close" in MyText:
                    MyText = MyText.replace("close ", "")
                    Speak(f"Closing {MyText}")
                    x = closeApp(MyText)
                    if not x:
                        speakPrint(
                            f"Nothing found, Please Make Sure That the name is the same in The Task Manager"
                        )
                    else:
                        speakPrint(f"{x} Closed")
                elif "check" in MyText and "update" in MyText:
                    if CheckUpdate(version):
                        speakPrint("Update Available")
                        wb.open_new_tab(
                            'https://thevirtualassistant.netlify.app/')
                    else:
                        speakPrint("You Are Running The Latest Version")
                elif "help" in MyText:
                    Speak("Check out our website")
                    wb.open_new_tab('https://thevirtualassistant.netlify.app/')
                # Shutdown
                elif "shutdown" in MyText or "shut down" in MyText:
                    if "after" in MyText:
                        time = ((get_hours(MyText) * 3600 +
                                 get_minutes(MyText) * 60))
                        os.system(f"Shutdown -s -t {time}")
                    else:
                        for i in range(11, 0, -1):
                            print(f"Shutting down in {i}")
                            sleep(1)
                        os.system("shutdown -s")

                # restart
                elif "restart" in MyText:
                    if "after" in MyText:
                        time = ((get_hours(MyText) * 3600 +
                                 get_minutes(MyText) * 60))
                        os.system(f"Shutdown -r -t {time}")
                    else:
                        for i in range(11, 0, -1):
                            print(f"Restarting in {i}")
                            sleep(1)
                        os.system("shutdown -r")
                elif "bye" in MyText or "quit" in MyText or "leave" in MyText or "stop" in MyText or "adios" in MyText:
                    Speak("it was an honor serving here ")
                    quit()

        except sr.RequestError as e:
            speakPrint("Could not request results; {0}".format(e))

        except sr.UnknownValueError:
            speakPrint("unknown error occured")

        word = get_word("stand_by")
        sleep(1)
        Speak(word)
        stand_by()
        Speak(get_word("after_stand_by"))
コード例 #7
0
    while wrong < len(stages) - 1:
        print("\n")
        msg = "Guess a letter: "
        char = input(msg)
        char = char.lower()

        if char in rletters:
            cind = rletters.index(char)
            board[cind] = char
            rletters[cind] = "$"
        else:
            wrong += 1

        print((" ".join(board)))
        e = wrong + 1
        print("\n".join(stages[0:e]))

        if "_" not in board:
            print("You win! The word was: \"{}\"".format(word))
            win = True
            break

    if not win:
        print("\n".join(stages[0:wrong]))
        print("You lose! The word was: {}".format(word))

    play_again()


play_hangman(words.get_word())