break the game when all the every element already filled - python

im still learning pyhton. and i try to figure out, How can i break the game when the all i(every element) already filled.
example:
d u c k
You Win!
import random
player = input("\nnama player:")
print("Welcome to the GuesOrd game", player.title() + ".")
print("\nKategori: Hewan")
words = ["duck", "chicken", "bird", "platypus"]
word = random.choice(words)
guesses = "
chance = 10
while True:
for i in word:
if i in guesses:
print(i, end=" ")
else:
print("_", end=" ")
guess = input("\nyour guess(only input 1 aplhabet):")[0]
if guess in word:
guesses += guess
elif guess not in word:
chance -= 1
print("wrong guess. Guess again!")
print("you have " + str(chance) + " chance left!")
if chance == 0:
print("\nGame Over!")
print("The Answer Is", word)
break

Many ways to kill a cat. But off the top of my head, I'd say use something like this whenever the user enters a correct letter:
if guess in word:
guesses += guess
if sorted(guesses) == sorted(word):
print("\nYou've won!")
print("Answer is", word)
break

Related

Why does my code ignore my if statement for my hangman game? (python)

I just had a question about the code that I wrote below. I was just wondering about the if statement that I wrote with the "if guess not in secret_word:". When I run it as it's currently written, the condition doesn't even run or appear. However, when I swap it with the for statement which I wrote above, it runs just fine. I'm a bit new to programming, and I was just wondering if anyone could help me out with this. Why does the order of conditions matter here?
'''
import random
from words import words
secret_word = random.choice(words)
secret_letters = list(secret_word)
blanks = " _ " * len(secret_word)
already_guessed = []
lives = 10
print(blanks)
def valid_guess(): # function to make sure the letter guessed is valid (ie, not previously guessed)
is_letter = True
lives = 10
while True:
guess = (input("\nGuess a letter:"))
if guess in already_guessed:
print("You have already guessed this letter")
elif len(guess) != 1:
print("Please guess a single letter:")
is_letter = False
elif guess not in "abcdefghijklmnopqrstuvwxyz":
print("Please guess a LETTER:")
is_letter = False
if is_letter:
already_guessed.append(guess)
for guess in secret_word:
if guess in already_guessed:
print(guess + " ", end = "")
else:
print(" - ", end = "")
if guess not in secret_word:
lives -= 1
print(f"You lost a life! You only have {lives}/10 left!")
while True:
valid_guess()
'''
You could try this:
if guess in secret_word:
if guess in already_guessed:
print(guess + " ", end = "")
else:
print(" - ", end = "")
elif guess not in secret_word:
lives -= 1
print(f"You lost a life! You only have {lives}/10 left!")

Putting guessed letters instead of dashes / Hangman / Python

i made hangman and am using this code. everything works fine, i just want to replace dashes in the list [lenghtDashes] with the correctly guessed letter in the corresponding place. i could not find any information online or here as well. maybe someone knows.
im open to any improvement suggestions as well.
secWord = input("What is the word for others to guess?: ")
life = 10
#starting information
i = 1
while i < 10:
print(".")
i += 0.01
#dots so players can not see the word
print("you have 10 tries to guess the word")
print("you will have to choose between gessing a letter (l) or a word (w) in start of every turn")
print("however, if you guess the word incorrectly you will lose immediately")
ans = input("are you ready to begin?: ")
while ans != "yes":
ans = input("now? ")
#rules
i = 1
while i < 10:
print(".")
i += 0.01
#dots for taking players to start
lenghtDashes = []
for letter in range(len(secWord)):
lenghtDashes.append("_")
#making dashes list
print("let's begin")
print("the word has " + str(len(secWord)) + " letters.")
appended = "".join(lenghtDashes)
print(appended)
#info for players
usedLetters = []
guessedLetters = []
wordLis = []
while life > 0 and ans != secWord:
print("are you guessing letter or a word?")
guessThing = input("l / w : ")
#for guessing a word
if guessThing == "w":
ans = input("What is the secret word?: ")
if ans == secWord:
print("Congratulations, you have guessed the right word\nYou won!")
else:
print("You guessed the word incorrectly\n The word was " + secWord + " \n You lost!")
exit()
#=================================================================
#for guessing a letter
elif guessThing == "l":
letList = [letter for letter in secWord]
guLett = input("Guess the letter \n(single letter only): ")
usedLetters.append(guLett)
if guLett in letList:
guessedLetters.append(guLett)
letListPlus = [letter for letter, x in enumerate(letList) if x == guLett]
letListPlusPlus = [num + 1 for num in letListPlus]
print("///")
print("///")
print("///")
print("Letters that you have used : " + str(usedLetters))
print("Letter that are correct: " + str(guessedLetters))
print("The position of letter " + str(guLett) + " is " + str(letListPlusPlus))
else:
print("///")
print("///")
print("///")
print("incorrect guess, you have " + str(life - 1) + " guesses remaining")
life = life - 1
print("Letters that you have used are: " + str(usedLetters))
print("Letter that are correct: " + str(guessedLetters))
#=================================================================
Whenever you need your in-progress word to be displayed (like "o_e_f_ow"), call this function:
def wordWithDashes(guessedLetters, letList):
return [letter if letter in guessedLetters else "_" for letter in letList]
It creates a new list from letList with missing letters replaced with "_". You can use str on it if you want a string result.
You don't need to keep track of lenghtDashes. Just compute it from the guessed letters and the actual word whenever you need it, as the code I provided does.

Python Wheel of Fortune accept the whole word

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.")

Nested While loop in hangman

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.

Check for repetition in input (Python)

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.

Categories