How do I end this game? If the whole word is guessed it's over or you loose all life, but I am unable to end it if someone guesses all letters one by one.
secret_word = "something".upper()
lifes = u'\u2764'
total_lifes = 5
print("You have 5 lifes in total to guess the answer")
guess = None
for_list = "?"*len(secret_word)
my_list = list(for_list)
def change_user_output(value):
for j in range(0, len(secret_word)):
if (value == secret_word[j]):
my_list[j] = value
new_user_output = " ".join(my_list)
print(new_user_output)
while total_lifes > 0:
print(lifes * total_lifes)
print("Guess any letter : ")
guess = input().upper()
if(guess == secret_word):
print("WOW that is correct, the secret word is %s"%secret_word)
break
if(guess in secret_word):
print("You guessed it right %s is in SECRET WORD"%guess)
change_user_output(guess)
else:
print("There is no such letter in the SECRET WORD, you loose a life")
change_user_output(guess)
total_lifes -= 1
if total_lifes == 0:
print("You've lost all lifes, GAME OVER FOR YOU")
print("The SECRET WORD was : %s"%"".join(secret_word))
The problem is that if (guess == secret_word): will always be False since guess is a single letter and it gets replaced by a new input every iteration guess = input().upper(). So your loop will never quit in case of correct guess, it will quit only when you finish the lives.
You could add the following to check if the guessed letters match those in the secret word:
if(guess in secret_word):
print("You guessed it right %s is in SECRET WORD"%guess)
change_user_output(guess)
# New code below here.
if set(list(secret_word)) == set(my_list):
print("WOW that is correct, the secret word is %s"%secret_word)
break
You create a set of all letters needed. You add each guessed letter to another set.
If the set of needed letters is a subset of the guessed letters set, you are done:
secret_word = "apple".upper()
lifes = '#'
total_lifes = 5
print("You have 5 lifes in total to guess the answer")
guess = None
for_list = "?"*len(secret_word)
my_list = list(for_list)
characters_needed = set(secret_word) # set of all letters needed
characters_guessed = set() # set of guessed letters
len_secret = len(secret_word)
def change_user_output(value):
for j in range(0, len(secret_word)):
if (value == secret_word[j]):
my_list[j] = value
new_user_output = " ".join(my_list)
print(new_user_output)
while total_lifes > 0:
print(lifes * total_lifes)
print("Guess any letter : ")
guess = input().upper()
# check for correct lenghts of input:
if len(guess) not in (1,len_secret):
print("1 letter or the whole word! Try again.")
continue
if(guess == secret_word):
print("WOW that is correct, the secret word is {}".format(secret_word))
elif(len(guess) > 1):
print("Thats not the SECRET WORD.")
total_lifes -= 1
continue
# if you input a whole word, this will decrease the lives
# as no multiletter-input can be in your set of characters
if(guess in characters_needed):
print("You guessed it right {} is in SECRET WORD".format(guess))
characters_guessed.add(guess)
change_user_output(guess)
else:
print("There is no such letter in the SECRET WORD, you loose a life")
change_user_output(guess)
total_lifes -= 1
if (characters_needed.issubset(characters_guessed)):
print("You guessed all the characters. The secret word is {}".format(secret_word))
break
if total_lifes == 0:
print("You've lost all lifes, GAME OVER FOR YOU")
print("The SECRET WORD was : %s"%"".join(secret_word))
Output (for a,p,l,e):
#####
Guess any letter : a
You guessed it right A is in SECRET WORD
A ? ? ? ?
#####
Guess any letter : p
You guessed it right P is in SECRET WORD
A P P ? ?
#####
Guess any letter : l
You guessed it right L is in SECRET WORD
A P P L ?
#####
Guess any letter : e
You guessed it right E is in SECRET WORD
A P P L E
You guessed all the characgters. The secret word is APPLE
I also added some safeguarding around allowing whole word or 1 character to be inputted.
Related
I am doing a simple wheel of fortune program in python. I want the user to be able to win the game at any time by guessing the whole word, not just one letter at a time. How can I do that?
That's the logic of my code:
while guess in used:
print("You've already guessed the letter", guess)
guess = input("Enter your guess: ")
guess = guess.upper()
used.append(guess)
if guess in word:
print("\nYes!", guess, "is in the word!")
prize = random.randrange(500, 5000)
money = money + (prize* (correct+1))
# create a new so_far to include guess
new = ""
for i in range(len(word)):
if guess == word[i]:
new += guess
correct = correct + 1
else:
new += so_far[i]
so_far = new
elif guess == word:
print("YAY! You guessed the word.")
prize = random.randrange(500, 5000)
money = money + (prize* (correct+1)) # part where I am struggling with
else:
print("\nSorry,", guess, "isn't in the word.")
Used is the chars used and guess is the user's input
edit:
if so_far == word:
print("\nYou guessed it!")
print("\nThe word was", word)
print("\nYour cash prize is: ", money)
input("\n\nPress the enter key to exit.")
I don't see any code here to check if so_far is the whole word. I guess that's done after this code.
So just set so_far to the word when they guess the whole word. Then that other code will declare them the winner.
You also need to skip the if guess in word: test when guess is more than one character.
if len(guess) == 1 and guess in word:
print("\nYes!", guess, "is in the word!")
prize = random.randrange(500, 5000)
money = money + (prize* (correct+1))
# create a new so_far to include guess
new = ""
for i in range(len(word)):
if guess == word[i]:
new += guess
correct = correct + 1
else:
new += so_far[i]
so_far = new
elif guess == word:
print("YAY! You guessed the word.")
prize = random.randrange(500, 5000)
money = money + (prize* (correct+1)) # part where I am struggling with
so_far = word # add this line
else:
print("\nSorry,", guess, "isn't in the word.")
There is one small problem with my code , after I get all the letters correct, I had to enter another letter only it will show that I got it right. What is the problem?
import random
import string
import sys
def split(word):
return list(word)
alphabet = 'abcdefghijklmnopqrstuvwxyz'
list(alphabet)
words = ['hat','pop' ,'cut' , 'soup' , 'you' , 'me' , 'gay' , 'lol' ]
guess_word = []
wrong_letters_storage = []
secret_word = random.choice(words)
word_length = print("the length of the word is " + str(len(secret_word)))
correct_letters = split(secret_word)
def words():
for letter in secret_word:
guess_word.append("-")
return print("the words that you are guessing is " + str(guess_word))
def guessing():
while True:
c = 0
b = 7
while c <= 7:
print("")
hide = ""
print("you have " + str(b) + " guess left")
print("Wrong letters : " + str(wrong_letters_storage))
command = input("guess: ").lower()
if not '-' in guess_word:
print("you win!")
break
elif command == 'quit':
print("thank you for playing my game")
break
else:
if not command in alphabet :
print("pick an alphabet")
elif command in wrong_letters_storage:
print("you have picked this word")
else :
if command in secret_word :
print("right")
c += 1
b -= 1
for x in range(0, len(secret_word)):
if correct_letters[x] == command:
guess_word[x] = command
print(guess_word)
elif not command in secret_word :
print("wrong")
wrong_letters_storage.append(command)
c += 1
b -= 1
else :
print("error")
print("*"*20)
return print("Thank you for playing my game")
words()
guessing()
print("the words that you are guessing is " + secret_word )
Your code has several "problems":
you check if the current solution has no more '-' in it, after you ask for the next character input()
return print("whatever") returns None because the print function prints and returns None
you use variables with single_letter_names that make it hard to know what they are for
you use list's instead of set()'s for lookups (its fine here, but not optimal)
You can fix your problem by moving the test statement before the input() command:
# your code up to here
while True:
c = 0
b = 7
while c <= 7:
if not '-' in guess_word:
print("you win!")
break
print("")
hide = ""
print("you have " + str(b) + " guess left")
print("Wrong letters : " + str(wrong_letters_storage))
command = input("guess: ").lower()
if command == 'quit':
print("thank you for playing my game")
break
else:
# etc.
It would probably be better to do some more refaktoring:
import random
import string
import sys
def join_list(l):
return ''.join(l)
def guessing():
# no need to put all this in global scope
alphabet = frozenset(string.ascii_lowercase) # unchangeable set of allowed letters
words = ['hat', 'pop', 'cut', 'soup', 'you', 'me', 'beautiful', 'lol']
secret = random.choice(words) # your random word
secret_word = list(secret.lower()) # your random word as lowercase list
wrong = set() # set of wrongly guessed characters
right = set() # set of already correctly guessed characters
correct = frozenset(secret_word) # set of letters in your word, not changeable
guess_word = ['-' for k in correct] # your guessed letters in a list
guesses = 7
guessed = 0
print("The length of the word is ", len(secret))
# loop until breaked from (either by guessing correctly or having no more guesses)
while True:
print("")
print(f"you have {guesses-guessed} guess left")
if wrong: # only print if wrong letters guessed
print(f"Wrong letters : {wrong}")
# print whats know currently:
print(f"Guess so far: {join_list(guess_word)}")
command = input("guess: ").strip().lower()
try:
if command != "quit":
command = command[0]
except IndexError:
print("Input one letter")
continue
if command == 'quit':
print("thank you for playing my game")
break
else:
if command not in alphabet:
print("pick an alphabet")
continue
elif command in (wrong | right):
print("you already picked this letter")
continue
else :
guessed += 1
# always lookup in set of lowercase letters
if command in correct:
right.add(command)
for i,letter in enumerate(secret_word):
if command == letter:
# use the correct capitalisation from original word
guess_word[i] = secret[i]
else:
print("wrong")
wrong.add(command)
print("*"*20)
# break conditions for win or loose
if join_list(secret_word) == join_list(guess_word):
print("You won.")
break
elif guessed == guesses:
print(f"You lost. Word was: {join_list(secret_word)}")
break
guessing()
Im trying to create a for loop end game by doing for "every letter in my secret word if All letters are in gussed_letters then end game."
Ive tried to make a correct_letters list and see if all the letters in my secret word are in my correct_letters list then end the game but i cant seem to get it to work.
import random
words = ['apple',' python','parent'] #Make list of words
def randomword(words): #takes in list words
return random.choice(words) #returns a random element back
chosenword = randomword(words) # make a variable equal to the function
#variables (tries you get and list to letters gussed. )
tries = 10
guess_letters = []
def dashshow(guess_letters): #takes in guess_letters
for letter in chosenword: #checks each letter in chosenword
if letter in guess_letters: #if letter in guess_letters print that letter
print(letter)
else: #or else print a dash
print('-')
def playgame(tries):# Takes tries
while tries != 0: #While tries is not 0
guess = str(input("Guess a letter of the word: ")).lower() #Ask for a guess
guess_letters.append(guess) #add guess to guess_letters list
if guess in chosenword: #if your guess in chosenword
print("You got a letter correct!")
tries -= 1
elif guess not in chosenword:
print("That letter is not in the word")
tries -= 1
dashshow(guess_letters) # last call the dashshow function
randomword(words)
playgame(tries)
I made the dashshow function count how many dashes left and return a value for whether any are left. If not, the game is over and has been won.
import random
words = ['apple',' python','parent'] #Make list of words
def randomword(words): #takes in list words
return random.choice(words) #returns a random element back
chosenword = randomword(words) # make a variable equal to the function
#variables (tries you get and list to letters gussed. )
tries = 10
guess_letters = []
def dashshow(guess_letters): #takes in guess_letters
dashes = 0
for letter in chosenword: #checks each letter in chosenword
if letter in guess_letters: #if letter in guess_letters print that letter
print(letter)
else: #or else print a dash
print('-')
dashes = dashes+1
return(dashes>0)
def playgame(tries):# Takes tries
keepPlaying = True
while (tries != 0) and keepPlaying: #While tries is not 0
guess = str(input("Guess a letter of the word: ")).lower() #Ask for a guess
guess_letters.append(guess) #add guess to guess_letters list
if guess in chosenword: #if your guess in chosenword
print("You got a letter correct!")
tries -= 1
elif guess not in chosenword:
print("That letter is not in the word")
tries -= 1
if not dashshow(guess_letters): # last call the dashshow function
keepPlaying=False
print("you win!")
randomword(words)
playgame(tries)
you can create variable is list letters of secret word, remove letter if it similars guess
Try this
def playgame(tries):# Takes tries
chosenword_ = list(chosenword)
while tries != 0 and chosenword_: #While tries is not 0
guess = str(input("Guess a letter of the word: ")).lower() #Ask for a guess
guess_letters.append(guess) #add guess to guess_letters list
if guess in chosenword: #if your guess in chosenword
print("You got a letter correct!")
tries -= 1
try:
chosenword_.remove(guess)
except ValueError:
pass
elif guess not in chosenword:
print("That letter is not in the word")
tries -= 1
dashshow(guess_letters) # last call the dashshow function
I am creating a hangman game.Here are the conditions
User will be given six chances for wrong choices
If the letter was already entered, user will be notified that letter already exists (user will not be penalised for double wrong entry)
Now my question is :
I want to display the message that "user lost the game" if the number of wrong guessed letters goes to 7 and exists the loop but it is not happening
here is my code:
print("Welcome to Hangman"
"__________________")
word = "Python"
wordlist=list(word)
wordlist.sort()
print(wordlist)
print("Word's length is", len(word))
letter=" "
used_letter=[]
bad_letter=[]
guess=[]
tries=0
while len(bad_letter)<7:
while guess != wordlist or letter !="exit":
letter = input("Guess your letter:")
if letter in word and letter not in used_letter:
guess.append(letter)
print("good guess")
elif letter in used_letter:
print("letter already used")
else:
bad_letter.append(letter)
print("bad guess")
used_letter.append(letter)
tries+=1
print("You have ",6 - len(bad_letter), " tries remaining")
print(guess)
print("You have made ",tries," tries so far")
guess.sort()
print("Thank you for playing the game, you guessed in ",tries," tries.")
print("Your guessed word is", word)
print("you lost the game")
I am very new to python so i would appreciate help in basic concepts
It seems like your while len(bad_letter) < loop is never exiting because of the while loop below it which is checking for the right answer or exit entry runs forever.
What you should do is only have one master while loop which takes in a new input each time and then check to see if that input matches any of the conditions you are looking for.
You could structure it something like this:
bad_letter = []
tries = 0
found_word = False
while len(bad_letter) < 7:
letter = input("Guess your letter:")
if letter == 'exit':
break # Exit game loop
if letter in word and letter not in used_letter:
guess.append(letter)
print("good guess")
elif letter in used_letter:
print("letter already used")
else:
bad_letter.append(letter)
print("bad guess")
used_letter.append(letter)
tries+=1
print("You have ", 6 - len(bad_letter), " tries remaining")
print(guess)
print("You have made ",tries," tries so far")
guess.sort()
if guess == wordlist:
found_word = True
break # Exits the while loop
print("Thankyou for playing tha game, you guessed in ",tries," tries.")
print("Your guessed word is", word)
if found_word:
print("You won")
else:
print("you lost the game")
Solution
word = 'Zam'
guesses = []
guesses_string = ''
bad_guesses = []
chances = 6
def one_letter(message=""):
user_input = 'more than one letter'
while len(user_input) > 1 or user_input == '':
user_input = input(message)
return user_input
while chances > 0:
if sorted(word.lower()) == sorted(guesses_string.lower()):
print("\nYou guessed every letter! (" + guesses_string + ")")
break
guess = one_letter("\nGuess a letter: ")
if guess in guesses or guess in bad_guesses:
print("You already guessed the letter " + guess + ".")
continue
elif guess.lower() in word.lower():
print("Good guess " + guess + " is in the word!.")
guesses.append(guess)
guesses_string = ''.join(guesses)
print("Letters guessed: " + guesses_string)
else:
print("Sorry, " + guess + " is not in the word.")
bad_guesses.append(guess)
chances -= 1
print(str(chances) + " chances remaning.")
if chances == 0:
print("\nGame Over, You Lose.")
else:
word_guess = ''
while word_guess.lower() != word.lower():
word_guess = input("Guess the word: ('quit' to give up) ")
if word_guess.lower() == 'quit':
print("You gave up, the word was " + word.title() + "!")
break
if word_guess.lower() == word.lower():
print("\nCongratulations YOU WON! The word was "
+ word.title() + "!")
Hey there! I'm new to programming (week 2) and keep seeing these 'hangman' games popup, since today is my break from learning, I the goals you were trying to achieve and ran with it.
Added some extra features in here such as breaking the loop if the all letters are guessed, and then asking the user to guess the final word.
Notes
There is a ton of Refactoring you could do with this(almost breaks my heart to post this raw form) but I just blurted it on on the go.
Also note that my original goal was to stick to your problem of not allowing the same letter to be entered twice. So this solution only works for words that contain no duplicate letters.
Hope this helps! When I get some time I'll Refactor it and update, best of luck!
Updates
Added bad_guesses = [] allows to stop from entering bad guess twice.
How do i check for a repeating input(letter) for a hangman game?
Example:
word is apple
input is Guess a letter: a
output is Well Done!
then guess next word
input is Guess a letter: a
output should be you already guess that letter.
my codes:
def checkValidGuess():
word = getHiddenWord()
lives = 10
num = ["1","2","3","4","5","6","7","8","9",]
#guessed = ''
while lives != 0 and word:
print("\nYou have", lives,"guesses left")
letter = input("Guess a letter or enter '0' to guess the word: ")
if letter.lower() in word:
print("Well done!", letter, "is in my word!")
lives -= 1
elif len(letter)>1:
print("You can only guess one letter at a time!")
print("Try again!")
elif letter in num:
print("You can only input letter a - z!")
print("Try again!")
#elif letter in guessed:
#print("repeat")
elif letter == "0":
wword = input("What is the word?").lower()
if wword == word:
print("Well done! You got the word correct!")
break
else:
print("Uh oh! That is not the word!")
lives -= 1
#elif letter == "":
#print("Uh oh! the letter you entered is not in my word.")
#print("Try again!")
else:
print("Uh oh! the letter you entered is not in my word.")
print("Try again!")
lives -= 1
Thanks.
You could store the inputs in a list, let's call it temp.
Then you could check to see if the input exists in the list when the user goes to input a new letter.
guess = input()
if guess in temp:
print "You've already guessed {}".format(guess)
else:
#do whatever you want
Here's an easy way. Start by initializing a list:
guesses = []
Then in your loop:
letter = input("Guess a letter or enter '0' to guess the word: ")
if letter in guesses:
print("Already guessed!")
continue
guesses.append(letter)
So you probably want to invert the order of your checks in your program so that you deal with the try again stuff first. Following that change, add another condition that determines if the letter matches those already guessed. This results in something like:
already_guessed = set() # I made this a set to only keep unique values
while lives > 0 and word: # I changed this to test > 0
print(f"\nYou have {lives} guesses left") # I also added an f-string for print formatting
letter = input("Guess a letter or enter '0' to guess the word: ")
if len(letter) > 1:
print("You can only guess one letter at a time!")
print("Try again!")
continue # If you reach this point, start the loop again!
elif letter in already_guessed:
print("You already guessed that!")
print("Try again")
continue
elif letter in num:
print("You can only input letter a - z!")
print("Try again!")
continue
elif letter.lower() in word:
print("Well done!", letter, "is in my word!")
lives -= 1
else:
already_guessed.update(letter)
# It wasn't a bad character, etc. and it wasn't in the word\
# so add the good character not in the word to your already guessed
# and go again!
You would need to add your other conditional branches, but this should get you there. Good luck.