Home > Software engineering >  Hangman game, whenever I try to put the same alphabet twice it takes 2 lives instead of just taking
Hangman game, whenever I try to put the same alphabet twice it takes 2 lives instead of just taking

Time:08-24

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])

CodePudding user response:

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
  • Related