In: Computer Science
import time
import random
# Accepts user name
playerName = input("Enter your name: ")
print ("Hello, " + playerName, " start the hangman game!")
print ("")
#wait for 1 second
time.sleep(1)
print ("Start guessing...")
time.sleep(0.5)
# Creates words
wordDic = ("danger", "apple", "easy", "democracy", "answer",
"question")
# Generates random word
secretWord = random.choice(wordDic)
print(secretWord)
# creates an variable with an empty value to store the guess
character
guessWord = ''
# Sets number of turns
turns = len(secretWord) + 1
# Create a while loop
#check if the turns are more than zero
while turns >= 0:
# make a counter that starts with zero
failed = 0
# Loops every character in secretWord
for char in secretWord:
# Checks if the character is in the players guess
if char in guessWord:
# Displays the character
print (char, end = '')
# if not found, print a dash symbol
else:
# Displays dash symbol separated by space
print ("_", end = ' ')
# Increase the failed counter with one
failed += 1
# Checks if failed is equal to zero
# print You Won
if failed == 0:
print ("\n You won")
# exit the script
break
# Displays how many turns are left
print ("\n You have", + turns, 'more guesses')
# Accepts a guess character
guessCharacter = input("\n Guess a character: ")
# Concatenates the players guess character to guess word
guessWord += guessCharacter
# Decrease the turn counter by one
turns -= 1
# Checks if the guess character is not found in the secret
word
if guessCharacter not in secretWord:
# Displays wrong
print ("Wrong")
# Checks if the turns are equal to zero
if turns == 0:
# Displays You Loose
print ("\n You Loose")
Sample Output:
Enter your name: Pyari
Hello, Pyari start the hangman game!
Start guessing...
_ _ _ _ _ _
You have 7 more guesses
Guess a character: t
Wrong
_ _ _ _ _ _
You have 6 more guesses
Guess a character: d
d_ _ _ _ _
You have 5 more guesses
Guess a character: g
d_ _ g_ _
You have 4 more guesses
Guess a character: n
d_ ng_ _
You have 3 more guesses
Guess a character: e
d_ nge_
You have 2 more guesses
Guess a character: r
d_ nger
You have 1 more guesses
Guess a character: a
danger
You won