Click here to Skip to main content
15,908,906 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
if guess != chosen_word:
lives -= 1
if lives == 0:
end_of_game = True
print("You lose.")


what is wrong with my code its only giving me 6 tries but the condition i have set is that if my choice is wrong then only my lives should - by 1

What I have tried:

import random


end_of_game = False
word_list = ["ardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)
word_length = len(chosen_word)


lives = 6

#Testing code
print(f'Pssst, the solution is {chosen_word}.')


display = []
for _ in range(word_length):
    display += "_"

while end_of_game == False:
    guess = input("Guess a letter: ").lower()

    
    for position in range(word_length):
        letter = chosen_word[position]

        if letter == guess:
            display[position] = letter


    if guess != chosen_word:
        lives -= 1
        if lives == 0:
            end_of_game = True
            print("You lose.")


    print(f"{' '.join(display)}")


    if "_" not in display:
        end_of_game = True
        print("You win.")
Posted
Updated 11-Oct-21 6:17am

1 solution

Python
# point 1
        if letter == guess:
            display[position] = letter


# point 2
    if guess != chosen_word:
        lives -= 1

1. If the letter is correct then you display it, but the word is still not complete.
2. You always check if the guess matches the chosen word. So even if the letter was correct the word does not match until you have all letters.

You need to rethink the choices and options. The word cannot be correct until you have all letters correct. However that could take forever, since even with short words there are plenty of letter choices. Maybe you should keep a count of the wrong letters rather than the word, and allow only some number of retries based on the word length. Perhaps three tries for each letter. Something like:
Python
for position in range(word_length):
    letter = chosen_word[position]

    if letter == guess:
        display[position] = letter
else:  # NB this else matches the for above, not the if
    lives -= 1
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900