that plays hangman game.
I guess a have an error in my guessWord(word) function, because its not working properly, and I'm not getting why?
the file for readDictionary contains rows of words for the game. but in the main code words can also be used.
current output:
Welcome to the hangman game.
You will be guessing words, one letter at a time
Guess a letter
a
Would you like to guess a new word? Y/N: y
Guess a letter
h
Would you like to guess a new word? Y/N: g
You guessed 2 words out of 2
desired output:
Your guess so far: -------
Guess a letter from the secret word: a
Good guess;
Your guess so far: -A----A
Guess a letter from the secret word: e
Wrong guess
--------
|
Your guess so far: -A----A
Guess a letter from the secret word: s
Wrong guess
--------
|
O
#and so on…
here are the parameters to do:
readDictionary() which reads the accompanying file “dictionary.txt” and returns a list of all the words appearing in the file.
• guessWord(word) which runs the user interface for guessing the word passed as argument, as described above. guessWord() calls hangmanSketch() with the appropriate argument, whenever a wrong guess is entered by the player.
Note that, even though all the words in the are in all-capital letters, the player should be able to enter the guesses in lower case.
The function returns True, if the player manages to guess the whole word before making 8 wrong guesses. The function returns False, if the player makes 8 wrong guesses and does not guess the whole word.
Below is an extract of a sample run of the whole application, showing the interface for successfully and unsuccessfully guessing words.
code:
from random import choice
def readDictionary():
file = open("dictionary.txt", "r")
lines = file.readlines()
return list(lines)
def hangmanSketch(n):
if n <= 0:
pic = ''' --------\n'''
return pic
pic = hangmanSketch(n-1)
if n == 1:
pic += ''' |\n'''
elif n == 2:
pic += ''' O\n'''
elif n == 3:
pic += '''_/'''
elif n == 4:
pic += '''|'''
elif n == 5:
pic += '''\_ \n'''
elif n == 6:
pic += ''' |\n'''
elif n == 7:
pic += '''_/'''
elif n == 8:
pic += ''' \_ \n'''
return pic
def guessWord(word):
while True:
print("Guess a letter")
userGuess = input()
userGuess = userGuess.lower()
if len(userGuess) != 1:
print("Please enter a single letter")
elif userGuess in word:
print("letter already guessed, try another")
else:
return userGuess
def main():
print("Welcome to the hangman game.")
print("You will be guessing words, one letter at a time")
words = readDictionary()
words = ['ABANDON', 'INQUIRING', 'LACROSSE', 'REINITIALISED'] # use this list if you don't manage to implement readDictionary()
nAttemptedWords = 0
nGuessedWords = 0
play = "Y"
while play == "Y":
secretWord = choice(words) # random choice of one word from the list of words
nAttemptedWords += 1
if guessWord(secretWord):
nGuessedWords += 1
play = input("Would you like to guess a new word? Y/N: ")
play = play.upper()
print("You guessed", nGuessedWords, "words out of", nAttemptedWords)
if __name__ == "__main__":
main()
I suggest you having one while for iterating between words and inner while for iterating through player's guesses:
import random
WORDS = ['abandon', 'inquiring', 'lacrosse', 'reinitialised']
def guessed_word(word, guessed_letters):
""" Build guessed word. E.g.: "--c--r" """
result = ''
for letter in word:
if letter in guessed_letters:
result += letter
else:
result += '-'
return result
print('Welcome to the hangman game.')
print('You will be guessing words, one letter at a time')
play = 'y'
while play == 'y':
word = random.choice(WORDS)
guessed_letters = []
hp = 8
while True:
print(f'Your guess so far: {guessed_word(word, guessed_letters)}')
letter = input('Guess a letter from the secret word: ')
if letter in list(word):
print('Good guess')
guessed_letters.append(letter)
else:
print('Wrong guess')
hp -= 1
if hp == 0:
print('You loose!')
break
elif len(guessed_letters) == len(set(word)):
print(f'You win! The word is: {word}')
break
play = input('Would you like to guess a new word? y/n: ')
Output:
Welcome to the hangman game.
You will be guessing words, one letter at a time
Your guess so far: --------
Guess a letter from the secret word: a
Good guess
Your guess so far: -a------
Guess a letter from the secret word: b
Wrong guess
Your guess so far: -a------
Guess a letter from the secret word: c
Good guess
Your guess so far: -ac-----
Related
I am a beginner in Python and I am making Hangman game project
So whenever I try to put the same alphabet twice it takes 2 lives
instead of just taking one
because both conditions are getting true.
My code is running fine but output is coming wrong due to both
conditions in if statement
given is satisfied
here is my code below
import time #importinf random module
#from hangman_art import logo #importing logo which i have in my PC, you ignore.
print("Welcome to HANGMAN")
#print(logo) #printing the logo which imported
user = input("\nWhat's Your Name : ") # take input for user name
print(f"\nHello {user}! Best Of Luck") #just for code to feel good.
x = (input("\nReady to play??? : ")) #input from user weather he/she wants to play or no.
if x == "yes" or x =="YES" or x =="Yes" or x == "y" or x == "Y": print("\nGame Loading in
3..2..1")
else:
print("\nOk Sadly ending the game!! BYE BYE")
exit()
#time.sleep(3)
print("\nGame Start!!")
#time.sleep(1)
print("\nRules as follows :-\n1. Guess the right word letter by letter.\n2. You only got 6
lives.\n3. Do not repeat the same alphabet entry it will reduce your life.\n4. Enjoy the game.")
#time.sleep(3)
import random #importing random module for code to choose any random number.
word_list=["TIGER","ELEPHANT","LION","CAT","DOG","HORSE"] #you can add n numbers of words.
chosen_word = random.choice(word_list) #giving variable to chosen random word.
length = len(chosen_word) #variable to find length of chosen word.
display=[] #creating an empty list.
in_game = True #for while loop to run continously
lives = 6 #user get 6 lives.
display=[]
duplicate=[] #creating an empty list to store duplicate values.
for _ in range (length):
display += "_"
#here looping for guess and game
while in_game:
guess = input("\nCome On Guess a word letter by letter : ").upper()
#make a list called duplicate
#add guess letter to duplicate list
#check if the entered letter is already present in that list
#if present then show msg stating already used word
#else follow the normal process
#duplicate=[]
if guess in display:
print("\nYou guessed",guess)
for position in range(length): #for getting length of number to be guessed
letter = chosen_word[position]
if letter == guess:
print("\nYou guessed",guess,"which is right aplhabet!!")
display[position] = letter
print(" ".join(display)) #joiningdisplay
if guess in duplicate:
lives -= 1 #this condition for taking life if duplicate entry.
print(f"\n{user} Do not repeat same alphabet entry. A LIFE LOST due to continues same
alphabet entry.") #here condition gets true and then goes to another if statment there also it gets true and code takes 2 life.
if lives == 0:
in_game = False
print(f"\n{user} You lost all your life, YOU LOSE.")
duplicate.append(guess)
#here 2 conditions are getting true so code is taking 2 lives please help
if guess not in chosen_word:
print("\nYou guessed", guess, "which is not the alphabet, life lost.")
lives -= 1
if lives == 0:
in_game = False
print(f"\n Try next
time {user}, You lost all your life, YOU LOSE.")
if not "_" in display:
in_game = False
print(f"\n Congrats {user} You WIN.")
from hangman_art import stages
print(stages[lives])
There are 2 if conditions that are true, so each will minus 1 live. You should use if and elif to ensure only 1 true condition is allowed. The code can be improved with 3 changes, see below:
<truncated>
while in_game:
guess = input("\nCome On Guess a word letter by letter : ").upper()
<truncated>
if guess in duplicate:
lives -= 1
print(f"\n{user} Do not repeat same alphabet entry. A LIFE LOST due to continues same alphabet entry.")
if lives == 0:
in_game = False
print(f"\n{user} You lost all your life, YOU LOSE.")
# duplicate.append(guess) #1. remove line from here
elif guess not in chosen_word: #2. change if to elif
print("\nYou guessed", guess, "which is not the alphabet, life lost.")
lives -= 1
if lives == 0:
in_game = False
print(f"\n Try next time {user}, You lost all your life, YOU LOSE.")
duplicate.append(guess) #3. add this line here instead
if not "_" in display:
in_game = False
print(f"\n Congrats {user} You WIN.")
Here's another way to do it, with MAX_WRONG = 6 means user gets 6 lives.
import random
WORDS = ['apple', 'banana', 'kiwi', 'orange', 'helicopter']
MAX_WRONG = 6
def game_play():
word = random.choice(WORDS).upper()
current_guess = '-' * len(word) #hidden answer
wrong_guesses = 0
used_letters = []
while wrong_guesses < MAX_WRONG and current_guess != word:
print ('\nRemaining tries:', MAX_WRONG - wrong_guesses)
print ('So far, the word is: ', current_guess)
print ('You have used the following letters: ', used_letters)
guess = input('Enter your letter guess:').upper()
if guess == word:
current_guess = word
break #exit the while-loop
while guess in used_letters: #check for duplicate input
print ('You have guessed "' + guess + '" already!')
guess = input ('Enter your letter guess: ').upper()
used_letters.append(guess) #append guess to used_letters
if guess in word:
print ('You have guessed correctly!')
new_current_guess = ''
for idx in range(len(word)): #update hidden answer
if guess == word[idx]:
new_current_guess += guess
else:
new_current_guess += current_guess[idx]
current_guess = new_current_guess
else:
print ('Sorry that was incorrect')
wrong_guesses += 1
if wrong_guesses == MAX_WRONG:
print ('\nYou have been hanged!')
print ('The correct word is', word)
elif current_guess == word:
print ('\nYou have won!! The word is:', word)
game_play()
Output:
Remaining tries: 6
So far, the word is: ----------
You have used the following letters: []
Enter your letter guess: helicopter
You have won!! The word is: HELICOPTER
Basically the title. I want my hangman game to generate a new random word from an imported file list every time I play again. However, when I do it it simply utilizes the same word as before. Here is the code.
import random
with open("English_Words", "r") as file:
allText = file.read()
words = list(map(str, allText.split()))
word = random.choice(words)}
def play_again():
print("Do you want to play again (Yes or No)")
response = input(">").upper()
if response.startswith("Y"):
return True
else:
return False
def singleplayer():
guessed = False
word_completion = "_" * len(word)
tries = 6
guessed_letters = []
while not guessed and tries > 0:
print(word_completion)
print(hangman_error(tries))
print(guessed_letters)
guess = input("Guess a letter:").lower()
if guess in guessed_letters:
print("You have already guessed that letter.")
elif guess not in word:
print("[INCORRECT] That letter is not in the word!")
guessed_letters.append(guess)
tries -= 1
if tries == 0:
print("You ran out of tries and hanged the man! The word or phrase was: " + str(word))
elif guess in word:
print("[CORRECT] That letter 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
if tries == 0:
print("You ran out of tries and hanged the man! The word or phrase was: " + str(word))
if "_" not in word_completion:
guessed = True
if guessed:
print("You win, the man was saved! The word was:" + str(word))
while True:
singleplayer()
if play_again():
continue
else:
break
You need to call word = random.choice(words) inside of your singleplayer() function. Preferrably at the top, either right above or right below the guess = False line.
This way, you're program is going to call that random choice line everytime you call the singleplayer function.
def singleplayer():
word = random.choice(words)
guessed = False
Q.Building Hangman Game. In the game of Hangman, the player only has 6 incorrect guesses (head, body, 2 legs, and 2 arms) before they lose the game. We loaded a random word list and picked a word from it. Then we wrote the logic for guessing the letter and displaying that information to the user. In this exercise, we have to put it all together and add logic for handling guesses.
So, I made the program with some help but stil there is a silly little problem coming that is the generation of a random word.
Please tell what I am doing wrong and if you would run this program that would help you better understand what I am saying.
import random
def generate():
Words = []
with open('sowpods.txt', 'r') as f:
line = f.readline().strip()
Words.append(line)
while line:
line = f.readline().strip()
Words.append(line)
index = random.randint(0, len(Words) - 1)
return Words[index]
def ask_user_for_next_letters():
letter = input("Guess Your Letter: ")
return letter.strip().upper()
def generate_word_string(word, letter_guessed):
output = []
for letter in word:
if letter in letter_guessed:
output.append(letter.upper())
else:
output.append("_")
return " ".join(output)
print("Welcome To Hangman!")
if __name__ == "__main__":
Secret = generate()
letter_to_guess = set(Secret)
correct_letters = set()
incorrect_letters = set()
num_guesses = 0
while (len(letter_to_guess) > 0) and num_guesses < 6:
guess = ask_user_for_next_letters()
#Checks If We Already Guessed That Letter
if guess in correct_letters or guess in incorrect_letters:
print("You Already Guessed That!")
continue
#If The Guess Was Correct
if guess in letter_to_guess:
#Update The letter_to_guess
letter_to_guess.remove(guess)
#Update The Correct Letters Guessed
correct_letters.add(guess)
else:
incorrect_letters.add(guess)
#Only Update The Number Of Guesses
#If You Guess Incorrectly
num_guesses += 1
word_string = generate_word_string(Secret, correct_letters)
print(word_string)
print("You Have {} Guesses Left".format(6 - num_guesses))
#Tell The User They Have Won Or Lost
if num_guesses < 6:
print("Congratulations! You Correctly Guessed The Word {}!".format(Secret))
else:
print("Loser!".format(Secret))
Modifications
Corrects routine generate to provide random words.
Always convert users input to uppercase
Convert selected word to upper case
slight change in variable naming so it conforms to PEP 8 (i.e. 'secret' rather than 'Secret')
Code
import random
def generate():
words = []
with open('sowpods.txt', 'r') as f:
for line in f:
line = line.strip()
if line:
words.append(line)
return random.choice(words).upper()
def ask_user_for_next_letters():
letter = input("Guess Your Letter: ")
return letter.strip().upper()
def generate_word_string(word, letter_guessed):
output = []
for letter in word:
if letter in letter_guessed:
output.append(letter.upper())
else:
output.append("_")
return " ".join(output)
if __name__ == "__main__":
print("Welcome To Hangman!")
secret = generate()
letter_to_guess = set(secret)
correct_letters = set()
incorrect_letters = set()
num_guesses = 0
while (len(letter_to_guess) > 0) and num_guesses < 6:
guess = ask_user_for_next_letters()
#Checks If We Already Guessed That Letter
if guess in correct_letters or guess in incorrect_letters:
print("You Already Guessed That!")
continue
#If The Guess Was Correct
if guess in letter_to_guess:
#Update The letter_to_guess
letter_to_guess.remove(guess)
#Update The Correct Letters Guessed
correct_letters.add(guess)
else:
incorrect_letters.add(guess)
#Only Update The Number Of Guesses
#If You Guess Incorrectly
num_guesses += 1
word_string = generate_word_string(secret, correct_letters)
print(word_string)
print("You Have {} Guesses Left".format(6 - num_guesses))
#Tell The User They Have Won Or Lost
if num_guesses < 6:
print("Congratulations! You Correctly Guessed The Word {}!".format(secret))
else:
print("Loser!".format(secret))
Im trying to make my for loop return a string of the whole word with a dash or each letter depending on guess_letters instead of print out each letter one by one for my hangman game.
Ive tried to print letter as a string, return letter then set a variable to that function then print the variable.
import random
words = ['apple','python','parent']
def randomword(words):
return random.choice(words)
chosenword = randomword(words)
tries = 10
guess_letters = []
def dashshow(guess_letters):
for letter in chosenword:
if letter in guess_letters:
return str(letter)
string_letter = dashshow(guess_letters)
print(string_Letter)
else:
return '-'
dash_letter = dashshow(guess_letters)
print(dash_letter)
def playgame(tries):
while tries != 0 and "_" in chosenword:
print(f"You have {tries} tries left")
guess = str(input("Guess a letter of the word")).lower()
guess_letters.append(guess)
if guess in chosenword:
print("You got a letter correct!")
turns -= 1
else:
print("That letter is not in the word")
turns -= 1
playgame(tries)
I thought it would print out the string with dashes or letters depending on the guessed_letters list but it doesn't print anything.
here is way you can. just modify as you need.Also, You can compare your code with this one. to find mistake.
import random
words = ['apple','python','parent']
def randomword(words):
return random.choice(words)
chosenword = randomword(words)
print (chosenword) #this is random word you can delete this line.
tries = 10
guess_letters = []
def dashshow(guess_letter):
guess_letters.append(guess_letter)
print(guess_letters) # just to debug you can remove.
if len(guess_letters) == len(chosenword):
print("You Won Dear!")
exit()
def playgame(tries):
while tries != 0 :
print(f"You have {tries} tries left")
guess = str(input("Guess a letter of the word:> ")).lower()
if any(guess in s for s in chosenword):
print("You got a letter correct!")
dashshow(guess)
tries -= 1
else:
print("That letter is not in the word")
tries -= 1
playgame(tries)
I am creating a "guess the word" game in python for my intro to programming class. The word is shown with dashes (-) in place of the vowels. The user is supposed to guess the word based off of a provided hint (the words/hints go together as parallel tuples). The user gets 5 guesses and if the word is guessed correctly, a certain amount of points are awarded. The user can then either choose to keep playing & accumulate points, or quit. The code was working until I added the coding to ask the user if he/she would like to keep playing. What is it that I need to fix in order for it to work?
#Clear Screen
print("\n"*50)
import random
#Variables
keep_playing = "y"
round_score = 0
overall_score = 0
new_words = ""
vowels = "AaEeIiOoUuYy"
#Parallel tuples
while keep_playing.lower() == "y":
guesswords = ("Japan","France","Mexico","Italy","Australia")
guesshints = ("Sushi comes from here","Croissants come from here","Tacos come from here","Pizza comes from here","Vegemite comes from here")
#Random
index = random.randrange(len(guesswords))
guesses = 5
#Replacing vowels
for letter in guesswords[index]:
if letter not in vowels:
new_words += letter
else:
new_words += "-"
#Output
print(new_words.center(80, " "))
print("Hint:",guesshints[index])
while guesses > 0:
input_string = "\nGuess the word! You have " + str(guesses) + " guesses remaining: "
user_guess = input(input_string)
if user_guess.upper() == guesswords[index].upper():
print("YOU WIN")
round_score = (guesses * 2)
overall_score += round_score
print("Your score for this round is ",round_score)
break
guesses -= 1
print("Your overall score is ",overall_score)
keep_playing = input("Would you like to keep playing? (y/n)")
print("GAME OVER")