Beispiel #1
0
def main():
    word_list = ['easter', 'program', 'receive', 'positive', 'study', \
        'computer', 'science', 'hangman', 'homework', 'queue',
        'stack', 'practice', 'example', 'quick']

    index = random.randint(0, len(word_list) - 1)
    game = hangman.Hangman(word_list[index], MAX_WRONG_GUESSES)

    print('\n*** Welcome to the Hangman Game ***')

    print('\nThis program will allow you to play the classic word guessing')
    print('game of hangman. You will be allowed a maximum of %d wrong guesses.' \
        % MAX_WRONG_GUESSES)
    print('Guessing the same wrong letter twice does not count against you.\n')

    while (not game.game_over()):
        print('\nThe current word is: %s' % game.get_guessed_word())
        letter = input('Choose a letter: ').lower()
        if (not game.guess(letter)):
            print('  Incorrect letters = %s' % game.get_missed_letters())

    if game.game_won():
        print('\nCongratulations!  You guessed the word %s.' \
            % game.get_word())
    else:
        print('\nYou lost! The correct word was %s.' % game.get_word())
Beispiel #2
0
def start_hangman():
    global game
    if game == None:
        global game_state
        game = "Hangman"
        game_state = hangman.Hangman()
        print("made " + game)
        return question(game_state.start_hint())
    return question("I misheard you. Please try again")
Beispiel #3
0
def hangman_start():
    palavra = str(input("Digite a palavra a ser colocada na força: ")).upper()
    dica = str(input("Dica: "))
    continuar = True
    jogo = hangman.Hangman(palavra, dica)

    print(jogo.hangman_map())

    while continuar:

        chute = chute_validacao()
        print(chute)
        print(jogo.hangman_map(chute))

        continuar = False if jogo.ganhou() in ("Você Ganhou",
                                               "Você Perdeu") else True

        if not continuar:
            print(f"Palavra: {palavra}")
            print(jogo.ganhou())
Beispiel #4
0
    print()
    print()
    print("Your guessed letters: ")
    print_array(guessed_letters)
    print()


if __name__ == "__main__":
    while True:
        play_again = True
        if play_again:
            random_word = generator.get_word().lower()
            guessed_letters = []
            word_array = generate_array(random_word)

            game = hangman.Hangman()
            print()
            print("""Welcome to Hangman
To play just guess a letter if the letter is in the word it will be added
if not you get a body part on the hanged man""")

            while True:

                game_engine()
                if check_if_won(word_array, game):
                    display_last_board()
                    if play_again_won():
                        play_again = True
                        break
                    else:
                        print("Press Enter to exit the game")
Beispiel #5
0
    if dbh.database is None:
        dbh.set_database(bot)
        await bot.loop.create_task(loop_save())


@bot.event
async def on_guild_join(guild):
    while dbh.database is None:
        await sleep(1)
    dbh.database.add_guild(guild.id)


@bot.event
async def on_message(message):
    if message.guild is not None:
        if message.channel.id == dbh.database.db['guilds'][
                message.guild.id]['counting']['channel']:
            await counting.handle_message(message)
    await bot.process_commands(message)


if __name__ == '__main__':
    try:
        bot.add_cog(counting.Counting(bot))
        bot.add_cog(rps.RockPaperScissors(bot))
        bot.add_cog(hangman.Hangman(bot))
        bot.add_cog(fun_cog.Fun(bot))
        bot.run(token)
    finally:
        running = False
        dbh.database.save_database()
            print(type(msg).__name__, msg)


RECV_BUFFER = 4096  # Advisable to keep it as an exponent of 2
PORT = 1337

SERVER_SOCKET = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
SERVER_SOCKET.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
SERVER_SOCKET.bind(("", PORT))  # empty addr string means INADDR_ANY
print("Listening...")
SERVER_SOCKET.listen(10)  # 10 connections

CONNECTION_LIST.append(SERVER_SOCKET)
print("Server started!")

game = hangman.Hangman(broadcast_all_encode)
while True:
    # Get the list sockets which are ready to be read through select
    READ_SOCKETS, WRITE_SOCKETS, ERROR_SOCKETS = select.select(
        CONNECTION_LIST, [], [])
    for SOCK in READ_SOCKETS:  # New connection
        # Handle the case in which there is a new connection recieved through server_socket
        if SOCK == SERVER_SOCKET:
            SOCKFD, ADDR = SERVER_SOCKET.accept()
            CONNECTION_LIST.append(SOCKFD)  # add socket descriptor
            # Adding \r to prevent message overlapping when another user
            # types it's message.
            print("\rClient ({0}, {1}) connected".format(ADDR[0], ADDR[1]))
            broadcast_all("Client ({0}:{1}) entered room\n".format(
                ADDR[0], ADDR[1]).encode())
            broadcast_to(SOCKFD,
Beispiel #7
0
import sys
import hangman

#Checks if the user gave us an alternative word list
if len(sys.argv) < 1:
    wordListPath = sys.argv[1]
else:
    wordListPath = "../data/wordlist"

hangman_game = hangman.Hangman(wordListPath)
hangman_game.start_game()
Beispiel #8
0
#!usr/bin/python
import hangman

game = hangman.Hangman("test", 5)

#loops until game is done
while True:
    status = game.isDone()  #checks if done
    if (status == 1):
        print "You win"
        break
    if (status == -1):
        print "You lose"
        break

    print "".join(game.display)  #prints the display list as a string

    guess = raw_input("Enter your guess: ")

    guessStatus = game.makeGuess(guess)

    if (guessStatus == -2):
        print "Invalid guess, try again"
    elif (guessStatus == -1):
        print "You have already guessed that"
    elif (guessStatus == 0):
        print "That guess was wrong"

    print "\n ****************** \n"
Beispiel #9
0
def main():

    # Get Nao's vocabulary
    vocabulary = alphabet.keys().tolist()
    fb_vocabulary = fb_dict.keys().tolist()

    if NAO_AVAILABLE:
        # NAO parser
        parser = OptionParser()
        parser.add_option("--pip",
            help="Parent broker port. The IP address or your robot",
            dest="pip")
        parser.add_option("--pport",
            help="Parent broker port. The port NAOqi is listening to",
            dest="pport",
            type="int")
        parser.set_defaults(
            pip=NAO_IP,
            pport=NAO_PORT)

        (opts, args_) = parser.parse_args()
        pip   = opts.pip
        pport = opts.pport

        # We need this broker to be able to construct
        # NAOqi modules and subscribe to other modules
        # The broker must stay alive until the program exists
        myBroker = ALBroker("myBroker",
           "0.0.0.0",   # listen to anyone
           0,           # find a free port and use it
           pip,         # parent broker IP
           pport)       # parent broker port

    # Initialze
    socialInteraction_fran.greeting(NAO_AVAILABLE)


    # Start the game
    social_interaction.nao_speech(["Okay, let's start with the hang man game"], NAO_AVAILABLE)
    social_interaction.nao_speech(["Let me think about a word"], NAO_AVAILABLE)


    if NAO_AVAILABLE:
        ledsProxy.fadeRGB("FaceLeds", 1 * 1 * 255, 1)
        ledsProxy.fadeRGB("FaceLeds", 1 * 256 * 255, 1)
        ledsProxy.fadeRGB("FaceLeds", 79 * 256 * 255, 1)
        ledsProxy.fadeRGB("FaceLeds", 44 * 1 * 255, 1)
        ledsProxy.fadeRGB("FaceLeds", 226 * 245 * 222, 1)

    social_interaction.nao_speech(["Okay got one"], NAO_AVAILABLE)
    time.sleep(1)

    # Read list of words for hangman  
    dictionary = pd.read_csv(os.path.join("dictionaries", "dict_en.txt"), sep = '\n').iloc[:, 0].values.tolist()
    
    # Create an instance of a hangman game
    hangman_game = hangman.Hangman(dictionary)


    i = 0  # Counter for while loop
    user_canceled = False
    status = 2 # 2 means game is running

    while status == 2:


        print("user_canceled is", user_canceled)

        if i == 0:
            # For example: "Please guess a letter"
            # First guess
            social_interaction.nao_speech(["Please make your first guess"], NAO_AVAILABLE)

        elif user_canceled:
            social_interaction.nao_speech(ask_repeat, NAO_AVAILABLE)
            user_canceled = False

        else:
            social_interaction.nao_speech(text_guess_letter, NAO_AVAILABLE)
        
            
        if NAO_AVAILABLE:
            # Include if we want to use events instead of a continuous speech recognition
            global SpeechEventListener
            SpeechEventListener = SpeechEventModule("SpeechEventListener", vocabulary)

            # Wait for first input
            while True:
                guess_long = memory.getData("WordRecognized")[0]
                if guess_long != '':
                    break
                # Check three times per second
                time.sleep(0.33)

        else:
            # Text input
            guess_long = raw_input("DEBUG: Please make a guess (from NATO alphabet):   ")

        # Get letter based on NATO word
        if guess_long in alphabet.index:
            guess = alphabet[guess_long]
        else:
           social_interaction.nao_speech(["This letter is not part of the Nato alphabet"],
                                         NAO_AVAILABLE)
           i += 1
           continue
    

        # Break the entire interaction on saying stop
        # TODO: another safe word would be better
        if guess == 'Stop':
            break

        # Repeat letter
        repeat_letter = [sentence + guess + '?' for sentence in text_repeat]
        social_interaction.nao_speech(repeat_letter, NAO_AVAILABLE)

        if NAO_AVAILABLE:
            # Start to listen for confirmation
            # memory.unsubscribeToEvent("WordRecognized", "SpeechEventListener")                
            global SpeechEventListener2
            SpeechEventListener2 = SpeechEventModule("SpeechEventListener", fb_vocabulary)

            feedback = None
            for timer in range(10):
                interrupt = memory.getData("WordRecognized")[0]
                print(interrupt)
                if interrupt != '':
                    feedback = fb_dict[interrupt]
                    break
                # Check three times per second
                time.sleep(0.33)                    

                # If user wanted to have another letter 
            print("feedback is", feedback)
            if feedback == 'No':
                user_canceled = True
                i += 1
                continue


        # THIS IS THE BEGINNING OF THE INTERFACE

        # Determine if the letter was in word
        letter_was_in_word = hangman_game.make_guess(guess)
        
        # END OF INTERFACE

        # Determine status of the letter (0: wrong, 1: right, 2: repeated)
        if letter_was_in_word == 1:
            social_interaction.nao_speech(text_guess_right, NAO_AVAILABLE)

        if letter_was_in_word == 2:
            social_interaction.nao_speech(text_guess_repeated_letter, NAO_AVAILABLE)

        if letter_was_in_word == 0:
            social_interaction.nao_speech(text_guess_wrong, NAO_AVAILABLE)

        hangman_game.print_status()

        status = hangman_game.get_status()

        # Determine game status
        if status == 0:
            social_interaction.nao_speech(text_loser, NAO_AVAILABLE)
            if NAO_AVAILABLE:
                social_interaction.winner_move()
        if status == 1:
            social_interaction.nao_speech(text_winner, NAO_AVAILABLE)
            if NAO_AVAILABLE:
                social_interaction.loser_move()

        i += 1

    
    social_interaction.nao_speech(["This is the end, my friend. Bye bye, H R I people"], NAO_AVAILABLE)

    if NAO_AVAILABLE:
        social_interaction.wave()
Beispiel #10
0
 def __init__(self):
     self.hangman = hangman.Hangman()
     self.loaded = False
Beispiel #11
0
 def testHangman(self):
     hang = hangman.Hangman()
     self.assertEqual(hang.remainingLives, 6)
     hang.decreaseLife()
     self.assertEqual(hang.remainingLives, 5)
Beispiel #12
0
def main():

    # NAO parser
    parser = OptionParser()
    parser.add_option("--pip",
                      help="Parent broker port. The IP address or your robot",
                      dest="pip")
    parser.add_option(
        "--pport",
        help="Parent broker port. The port NAOqi is listening to",
        dest="pport",
        type="int")
    parser.set_defaults(pip=NAO_IP, pport=9559)

    (opts, args_) = parser.parse_args()
    pip = opts.pip
    pport = opts.pport

    # Automatic speech recognition
    asr = ALProxy("ALSpeechRecognition", NAO_IP, 9559)
    asr.setLanguage("English")

    vocabulary = raw_alphabet.Word.values.tolist()
    asr.setVocabulary(vocabulary, False)

    # We need this broker to be able to construct
    # NAOqi modules and subscribe to other modules
    # The broker must stay alive until the program exists
    myBroker = ALBroker(
        "myBroker",
        "0.0.0.0",  # listen to anyone
        0,  # find a free port and use it
        pip,  # parent broker IP
        pport)  # parent broker port

    # Text to Speech
    tts = ALProxy("ALTextToSpeech", NAO_IP, 9559)
    tts.enableNotifications()

    # Include if we want to use events instead of a continuous speech recognition
    #global SpeechEventListener
    #SpeechEventListener = SpeechEventModule("SpeechEventListener")

    # Start the game

    #tts.say("Welcome to our Hangman game")

    dictionary = pd.read_csv("dict_en.txt", sep='\n').iloc[:,
                                                           0].values.tolist()
    hangman_game = hangman.Hangman(dictionary)

    memory = ALProxy('ALMemory', NAO_IP, 9559)

    while True:
        tts.say("Please guess a letter")

        # Start the speech recognition engine with user Test_ASR
        asr.subscribe("Test_ASR")
        time.sleep(3)
        guess_long = memory.getData("WordRecognized")[0]

        if guess_long != '':
            guess = alphabet[guess_long]
            tts.say("You guessed the letter: " + guess)

        asr.unsubscribe("Test_ASR")

        if guess_long != '':
            letter_was_in_word = hangman_game.make_guess(guess)

            if letter_was_in_word:
                tts.say("Your guess was right")

            else:
                tts.say("Your guess was wrong")

            hangman_game.print_status()

        if hangman_game.is_over():
            tts.say("Loser")
            break
Beispiel #13
0
"""
The main method that runs the game of Hangman.

This Hangman game is run in the console/command shell.

Author: Will Xiao
Date: Jan 4, 2019
"""
import hangman


def prompt_user_play():
    """
    Returns: True if the player wants to play another game of Hangman,
    False otherwise.
    """
    inp = ''
    while not inp in ['y', 'n']:  #invalid or valid input
        inp = input("Play again? Please enter either 'Y' or 'N'. ").lower()
    return inp == 'y'


if __name__ == '__main__':
    play_again = True
    while play_again:
        hangman.Hangman().play()
        play_again = prompt_user_play()