Answers for "how to make hangman in python"

10

python hangman

#first i have to say, i didn't develope this all by myself. I tried, but with the "display_hangman" function i needed help.
import random
word_list = ["insert", "your", "words", "in", "this", "python", "list"]

def get_word(word_list):
    word = random.choice(word_list)
    return word.upper()


def play(word):
    word_completion = "_" * len(word)
    guessed = False
    guessed_letters = []
    guessed_words = []
    tries = 6
    print("Let's play Hangman")
    print(display_hangman(tries))
    print(word_completion)
    print("n")
    while not guessed and tries > 0:
        guess = input("guess a letter or word: ").upper()
        if len(guess) == 1 and guess.isalpha():
            if guess in guessed_letters:
                print("you already tried", guess, "!")
            elif guess not in word:
                print(guess, "isn't in the word :(")
                tries -= 1
                guessed_letters.append(guess)
            else:
                print("Nice one,", guess, "is in the word!")
                guessed_letters.append(guess)
                word_as_list = list(word_completion)
                indices = [i for i, letter in enumerate(word) if letter == guess]
                for index in indices:
                    word_as_list[index] = guess
                word_completion = "".join(word_as_list)
                if "_" not in word_completion:
                    guessed = True
        elif len(guess) == len(word) and guess.isalpha():
            if guess in guessed_words:
                print("You already tried ", guess, "!")
            elif guess != word:
                print(guess, " ist nicht das Wort :(")
                tries -= 1
                guessed_words.append(guess)
            else:
                guessed = True
                word_completion = word
        else:
            print("invalid input")
        print(display_hangman(tries))
        print(word_completion)
        print("n")
    if guessed:
        print("Good Job, you guessed the word!")
    else:
        print("I'm sorry, but you ran out of tries. The word was " + word + ". Maybe next time!")




def display_hangman(tries):
    stages = [  """
                   --------
                   |      |
                   |      O
                   |     \|/
                   |      |
                   |     / \
                   -
                   """,
                   """
                   --------
                   |      |
                   |      O
                   |     \|/
                   |      |
                   |     /
                   -
                   """,
                   """
                   --------
                   |      |
                   |      O
                   |     \|/
                   |      |
                   |
                   -
                   """,
                   """
                   --------
                   |      |
                   |      O
                   |     \|
                   |      |
                   |
                   -
                   """,
                   """
                   --------
                   |      |
                   |      O
                   |      |
                   |      |
                   |
                   -
                   """,
                   """
                   --------
                   |      |
                   |      O
                   |
                   |
                   |
                   -
                   """,
                   """
                   --------
                   |      |
                   |      
                   |
                   |
                   |
                   -
                   """
    ]
    return stages[tries]

def main():
    word = get_word(word_list)
    play(word)
    while input("Again? (Y/N) ").upper() == "Y":
        word = get_word(word_list)
        play(word)

if __name__ == "__main__":
    main()
Posted by: Guest on July-08-2020
3

create a hangman game with python

#importing the time module
import time

#welcoming the user
name = raw_input("What is your name? ")

print "Hello, " + name, "Time to play hangman!"

print "
"

#wait for 1 second
time.sleep(1)

print "Start guessing..."
time.sleep(0.5)

#here we set the secret
word = "secret"

#creates an variable with an empty value
guesses = ''

#determine the number of turns
turns = 10

# Create a while loop

#check if the turns are more than zero
while turns > 0:         

    # make a counter that starts with zero
    failed = 0             

    # for every character in secret_word    
    for char in word:      

    # see if the character is in the players guess
        if char in guesses:    
    
        # print then out the character
            print char,    

        else:
    
        # if not found, print a dash
            print "_",     
       
        # and increase the failed counter with one
            failed += 1    

    # if failed is equal to zero

    # print You Won
    if failed == 0:        
        print "
You won"  

    # exit the script
        break              

    print

    # ask the user go guess a character
    guess = raw_input("guess a character:") 

    # set the players guess to guesses
    guesses += guess                    

    # if the guess is not found in the secret word
    if guess not in word:  
 
     # turns counter decreases with 1 (now 9)
        turns -= 1        
 
    # print wrong
        print "Wrong
"    
 
    # how many turns are left
        print "You have", + turns, 'more guesses' 
 
    # if the turns are equal to zero
        if turns == 0:           
    
        # print "You Lose"
            print "You Lose
"
Posted by: Guest on June-19-2020
1

hangman python

# i know its very messy but it was my first try to make something with python ~regards vga
import random

words = ['tree', 'mango', 'coding', 'human', 'python', 'java',
         'hangman', 'amazon', 'help', 'football', 'cricket', 'direction', 'dress', 'apology', 'driver', 'ship', 'pilot']
guess = words[random.randint(0, len(words)-1)].upper()
display = []
for x in guess:
    display.append("_")
print("*** GAME STARTED ****")
print("")
print("Guess the word ! ", end=" ")
indexes = []
limbs = 6
userWon = False
userLost = False
guessedLetters = []


def start(word, indexes, display, limbs, userWon, userLost, guessedLetters):
    chance = False  # to stop recursion
    wrong_guess = False
    word_found = ""  # change it to True or False based on word found in the word array
    if userLost == False:
        if len(indexes) > 0:  # check on recursion if user entered any correct letter
            for val in indexes:
                # loop to change "_" with the correct letter in array
                display[val] = word[val]
        if len(guessedLetters) > 0:
            # display how many limbs left
            print("You have ", limbs, " chances left")
            print("")
            print("Wrong Guesses", guessedLetters)
            print("")
        for dash in display:
            # print the display of "_" or the correct letter in the array
            print(dash, end=" ")
        print("")
        print("")
        user_guessed = input(
            "Guess by entering a letter or the complete word to win!: ").upper()
        if len(user_guessed) == 1:  # if user entered only a letter
            word_found = False
            for i in range(len(word)):  # to get the index of word array
                if(word[i] == user_guessed):  # match every single letter
                    if i in indexes:  # if user already guessed correct letter
                        print("You already guessed the letter ", word[i])
                        chance = True
                        word_found = True
                        break
                    else:
                        indexes.append(i)
                        print("Nice guess it was ", word[i])
                        word_found = True
        elif len(user_guessed) > 1:  # if used tried to guess by a word
            if(word == user_guessed):
                print("Woah luck is on your side, You won !")
                print("The correct word was ", word)
                userWon = True
            else:
                wrong_guess = True
        if user_guessed in guessedLetters:  # if user guessed wrong again with the same word/letter
            print("You already tried ", user_guessed)
            chance = True
        elif wrong_guess == True or word_found == False:  # when user guessed wrong reduce limbs
            guessedLetters.append(user_guessed)
            print("Eh, Wrong guess")
            limbs -= 1
            if limbs == 0:
                userLost = True
            else:  # when limbs are not 0 user can still play with chance = true
                chance = True
        if chance == True:
            start(word, indexes, display, limbs,
                  userWon, userLost, guessedLetters)
            chance = False  # to stop recursion :X aryan
        elif len(indexes) > 0 and userWon == False and userLost == False and chance == False:
            if len(indexes) == len(word):  # if user guessed all letters
                print("Woah, You won ! :)")
                print("The correct word was ", word)
            else:
                start(word, indexes, display, limbs,
                      userWon, userLost, guessedLetters)
        elif userLost == True:  # all limbs are 0 so user lost
            print("You have ", limbs, " chances left")
            print("Sorry, You lost :(")
            print("The correct word was ", word)


start(guess, indexes, display, limbs, userWon, userLost, guessedLetters)
Posted by: Guest on January-08-2021
0

hangman python code

  1. import random
  2. HANGMAN_PICS = ['''
  3.   +---+
  4.       |
  5.       |
  6.       |
  7.      ===''', '''
  8.   +---+
  9.   O   |
 10.       |
 11.       |
 12.      ===''', '''
 13.   +---+
 14.   O   |
 15.   |   |
 16.       |
 17.      ===''', '''
 18.   +---+
 19.   O   |
 20.  /|   |
 21.       |
 22.      ===''', '''
 23.   +---+
 24.   O   |
 25.  /|  |
 26.       |
 27.      ===''', '''
 28.   +---+
 29.   O   |
 30.  /|  |
 31.  /    |
 32.      ===''', '''
 33.   +---+
 34.   O   |
 35.  /|  |
 36.  /   |
 37.      ===''']
 38. words = 'ant baboon badger bat bear beaver camel cat clam cobra cougar
       coyote crow deer dog donkey duck eagle ferret fox frog goat goose hawk
       lion lizard llama mole monkey moose mouse mule newt otter owl panda
       parrot pigeon python rabbit ram rat raven rhino salmon seal shark sheep
       skunk sloth snake spider stork swan tiger toad trout turkey turtle
       weasel whale wolf wombat zebra'.split()
 39.
 40. def getRandomWord(wordList):
 41.     # This function returns a random string from the passed list of
           strings.
 42.     wordIndex = random.randint(0, len(wordList) - 1)
 43.     return wordList[wordIndex]
 44.
 45. def displayBoard(missedLetters, correctLetters, secretWord):
 46.     print(HANGMAN_PICS[len(missedLetters)])
 47.     print()
 48.
 49.     print('Missed letters:', end=' ')
 50.     for letter in missedLetters:
 51.         print(letter, end=' ')
 52.     print()
 53.
 54.     blanks = '_' * len(secretWord)
 55.
 56.     for i in range(len(secretWord)): # Replace blanks with correctly
           guessed letters.
 57.         if secretWord[i] in correctLetters:
 58.             blanks = blanks[:i] + secretWord[i] + blanks[i+1:]
 59.
 60.     for letter in blanks: # Show the secret word with spaces in between
           each letter.
 61.         print(letter, end=' ')
 62.     print()
 63.
 64. def getGuess(alreadyGuessed):
 65.     # Returns the letter the player entered. This function makes sure the
           player entered a single letter and not something else.
 66.     while True:
 67.         print('Guess a letter.')
 68.         guess = input()
 69.         guess = guess.lower()
 70.         if len(guess) != 1:
 71.             print('Please enter a single letter.')
72.         elif guess in alreadyGuessed:
 73.             print('You have already guessed that letter. Choose again.')
 74.         elif guess not in 'abcdefghijklmnopqrstuvwxyz':
 75.             print('Please enter a LETTER.')
 76.         else:
 77.             return guess
 78.
 79. def playAgain():
 80.     # This function returns True if the player wants to play again;
           otherwise, it returns False.
 81.     print('Do you want to play again? (yes or no)')
 82.     return input().lower().startswith('y')
 83.
 84.
 85. print('H A N G M A N')
 86. missedLetters = ''
 87. correctLetters = ''
 88. secretWord = getRandomWord(words)
 89. gameIsDone = False
 90.
 91. while True:
 92.     displayBoard(missedLetters, correctLetters, secretWord)
 93.
 94.     # Let the player enter a letter.
 95.     guess = getGuess(missedLetters + correctLetters)
 96.
 97.     if guess in secretWord:
 98.         correctLetters = correctLetters + guess
 99.
100.         # Check if the player has won.
101.         foundAllLetters = True
102.         for i in range(len(secretWord)):
103.             if secretWord[i] not in correctLetters:
104.                 foundAllLetters = False
105.                 break
106.         if foundAllLetters:
107.             print('Yes! The secret word is "' + secretWord +
                   '"! You have won!')
108.             gameIsDone = True
109.     else:
110.         missedLetters = missedLetters + guess
111.
112.         # Check if player has guessed too many times and lost.
113.         if len(missedLetters) == len(HANGMAN_PICS) - 1:
114.             displayBoard(missedLetters, correctLetters, secretWord)
115.             print('You have run out of guesses!nAfter ' +
                   str(len(missedLetters)) + ' missed guesses and ' +
                   str(len(correctLetters)) + ' correct guesses,
                   the word was "' + secretWord + '"')
116.             gameIsDone = True
117.
118.     # Ask the player if they want to play again (but only if the game is
           done).
119.     if gameIsDone:
120.         if playAgain():
121.             missedLetters = ''
122.             correctLetters = ''
123.             gameIsDone = False
124.             secretWord = getRandomWord(words)
125.         else:
126.             break
Posted by: Guest on July-13-2021
0

how to make a a msgbpx in vbs

msg "Box Message", Constant(s), "Title"
Posted by: Guest on March-14-2020
-2

Write the program to implement Hangman game.

#This game has pre-specified input 
import time
name = input("What is your name? ")
print("Hello, " + name, "Time to play hangman!")
print("")
time.sleep(1)
print("Start guessing...")
time.sleep(0.5)
word = "secret"
guesses = ''
turns = 10
while turns > 0:
    failed = 0
    for char in word:
        if char in guesses:
            print(char)
        else:
            print("_")
            failed += 1
    if failed == 0:
        print("You won")
        break
    print('')
    guess = input("guess a character:")
    guesses += guess
    if guess not in word:
        turns -= 1
        print("Wrong")
    print("You have", + turns, 'more guesses')
    if turns == 0:
        print("You Lose")
Posted by: Guest on May-17-2020

Code answers related to "how to make hangman in python"

Python Answers by Framework

Browse Popular Code Answers by Language