I want to create the hangman python game, so I created a simpler piece of the game. The idea of the game is to guess the letters in a randomly generated word. Here is what I have so far. I listed the problem and questions I have at the bottom.
import random
words = ['holiday', 'american', 'restaurant', 'computer', 'highschool', 'programming']
random_word = random.choice(words)
count = 0
while True: #repeatedly asks you to guess the letter in a random word
guess = str(input("Guess a letter: "))
guess = guess.lower()
if guess in random_word: #checks if the letter you input is in the random generated word
print("Yay, its in the word")
else:
count += 1
print("Not in the word, attempts: %d" % count)
if count > 5:
print("You have reached max attempts")
print("Sorry, but hangman died! You lose")
break
else:
continue
The problem I have: When the user guesses a letter, they can guess it again infinite times. How can I make it so that the user can't repeatedly guess the same letter?
Is there a way to make sure the user doesn't guess the same letter? This could be a problem in an actual hangman game when there are several letters that are the same. Any help/feedback appreciated, thanks!
Here is one way of doing it.
import random
words = ['holiday', 'american', 'restaurant', 'computer', 'highschool', 'programming']
random_word = random.choice(words)
count = 0
guess_list = []
while True: #repeatedly asks you to guess the letter in a random word
guess = str(input("Guess a letter: "))
guess = guess.lower()
if guess not in guess_list:
if guess in random_word: #checks if the letter you input is in the random generated word
print("Yay, its in the word")
else:
count += 1
print("Not in the word, attempts: %d" % count)
if count > 5:
print("You have reached max attempts")
print("Sorry, but hangman died! You lose")
break
else:
print("You have already guessed {}. Try again".format(guess))
print(set(guess_list))
guess_list.append(guess)
Sample output (word is computer):
Guess a letter: c
Yay, its in the word
Guess a letter: e
Yay, its in the word
Guess a letter: e
You have already guessed e. Try again
{'e', 'c'}
Guess a letter: e
You have already guessed e. Try again
{'e', 'c'}
Guess a letter: w
Not in the word, attempts: 1
Guess a letter: m
Yay, its in the word
Guess a letter: m
You have already guessed m. Try again
{'w', 'm', 'e', 'c'}
Guess a letter:
Notes:
A guess_list is created that keeps record of all the guesses.
After each guess the letter is appended to the list.
When the user repeats the guess they are warned. We use a set so only the unique elements in the guess list are displayed.
The code can be refined further, but must do the job.
Depending on the word, you may need to allow multiple guesses if the letter appears more than once. (this may not be your requirement. Not familiar with the game.)
Approach
What you need is a store that keeps track of the number of occurrences of each letter in the word.
Something like:
letterCounts = Counter("hello") # word: 'hello' => {'h': 1, 'e': 1, 'l': 2, 'o': 1}
I'm using the counter collection here.
Then you can decrement the count of the guessed letter
if guesses_letter in list(letterCounts.elements()):
if (letterCounts[guessed_letter] > 0):
letterCounts[guessed_letter] -= 1
else:
# the letter can't be repeated now. do the needful here.
Related
I have made a word guessing game but when it picks a random word with repeating letters in it, it works fine and puts the correctly guessed letters into a list. But how do I make it so it acknowledge that the random word has repeating letters so accepts repeating letters? For example, if the chosen word is ball and you entered s it would display that s is not in the word. If I entered l, it would say l is in the word and add it to a list called correct. If I then entered l again as ball has two l's, it will display that I have already entered that letter and will not let me continue any further. I don't know how I can make it acknowledge that the word has repeating letters. Here is the code:
words = ["burger","chips","ketchup","cake","crisp","coke","fruit"]
correct = []
guessed = []
print("Weclome to guess the word. Aim of the game is to guess all the letters in the word and then type what word you think the word is. The subject is food. You have 15 guesses")
j = random.choice(words)
x = len(j)
count = x
guesses = 15
print("The word is:", x , "letters long.")
while guesses > 0:
guess1 = input("Enter a letter: ").lower()
k = len(guess1)
if k != 1:
print("Not a valid guess!")
if guess1 in j and guess1 in correct:
print("You have already guessed this letter! Your number of guesses left is:", guesses)
if guess1 in j and guess1 not in correct:
print(guess1,"is in the word. You have:", guesses , "guesses left.")
correct.append(guess1)
guesses = guesses-1
count = count-1
print("You have", count ,"of", x , "letters left to guess and you correctly given these letters:", *correct)
if guess1 not in j and guess1 not in guessed:
guessed.append(guess1)
print(guess1, "is not in the word. You have:", guesses , "guesses left and have given the following incorrect letters:", *guessed)
guesses = guesses-1
if guesses == 0:
print("You have ran out of guesses!")
break
if count == 0:
print("Well done! You have guessed all the letters. Now time to de-scramble them! You have unlimited guesses for the word.")
print("These are the following letters you need to de-scramble")
print(*correct)
descramble = input("Enter what you think the word is: ").lower()
if descramble == j:
print("You guessed the word! Well done!")
break
if descramble != j:
print(descramble,"is not the word.")```
You can try this,
import random
words = ["burger","chips","ketchup","cake","crisp","coke","fruit"]
correct = []
guessed = []
print("Weclome to guess the word. Aim of the game is to guess all the letters in the word and then type what word you think the word is. The subject is food. You have 15 guesses")
j = random.choice(words)
x = len(j)
count = x
guesses = 15
already_used_letters = list()
print("The word is:", x , "letters long.")
while guesses > 0:
guess1 = input("Enter a letter: ").lower()
k = len(guess1)
if guess1 in already_used_letters:
print("You already used this letter")
guesses = guesses - 1
already_used_letters.append(guess1)
if k != 1:
print("Not a valid guess!")
if guess1 in j and guess1 in correct:
print("You have already guessed this letter! Your number of guesses left is:", guesses)
if guess1 in j and guess1 not in correct:
print(guess1,"is in the word. You have:", guesses , "guesses left.")
correct.append(guess1)
guesses = guesses-1
count = count-1
print("You have", count ,"of", x , "letters left to guess and you correctly given these letters:", *correct)
if guess1 not in j and guess1 not in guessed:
guessed.append(guess1)
print(guess1, "is not in the word. You have:", guesses , "guesses left and have given the following incorrect letters:", *guessed)
guesses = guesses-1
if guesses == 0:
print("You have ran out of guesses!")
break
if count == 0:
print("Well done! You have guessed all the letters. Now time to de-scramble them! You have unlimited guesses for the word.")
print("These are the following letters you need to de-scramble")
print(*correct)
descramble = input("Enter what you think the word is: ").lower()
if descramble == j:
print("You guessed the word! Well done!")
break
if descramble != j:
print(descramble,"is not the word.")
Try this:
import random
words = ["burger", "chips", "ketchup", "cake", "crisp", "coke", "fruit"]
correctLetters = []
wronglyGuessed = []
print(
"Weclome to guess the word. Aim of the game is to guess all the letters in the word and then type what word you think the word is. The subject is food. You have 15 guesses")
word = random.choice(words)
# word = "aapplle"
lives = 15
while lives > 0:
if len(word) == len(correctLetters):
print(
"Well done! You have guessed all the letters. Now time to de-scramble them! You have unlimited guesses for the word.")
print("These are the following letters you need to de-scramble")
print(*correctLetters)
descramble = input("Enter what you think the word is: ").lower()
if descramble == word:
print("You guessed the word! Well done!")
break
else:
print(descramble, "is not the word.")
guess1 = input("Enter a letter: ").lower()
if len(guess1) > 1 or not guess1.isalpha():
print("Not a valid guess!")
lives -= 1
continue
if guess1 in word:
if word.count(guess1) > correctLetters.count(guess1):
correctLetters.append(guess1)
print("you found a letter")
else:
lives -= 1
print('You guessed all the occurances')
continue
if guess1 not in word:
lives -= 1
print(f'Wrong guess. You have {lives} tries left')
continue
if lives == 0:
print("You ran out of guesses")
Your problem comes from here:
if guess1 in j and guess1 in correct:
print("You have already guessed this letter! Your number of guesses left is:", guesses)
When you use in it will only find the first occurrence of said item and return true. In this case you are interested in also finding the case for duplicates and also keeping track of them. Thus, you need to take another approach: that of finding said duplicates and their number. I used a pre-built method count().
I'd say there are a few more issues with your code:
Use descriptive names for your variables. x, j, k, n can mean a lot of things whereas guestNames is pretty self explanatory
When a case inside one of your ifs was met and all following tests cannot evaluate true, just use a continue statement
Also, on a different note, i'd say that when a letter is guessed you assume all its occurances, but that's not programming related.
I'm trying to create a hangman game. I have a feature that says if the letter that you chose is in a list of all the letters guessed, it will tell you that it has already been guessed. When i run the program it says that the letter has been guessed even though it hasn't been guessed or if it's the first letter that i guessed.
import random
print("---Hangman---")
WordList = ["programming", "computer", "game"]
LetterList = []
Word = random.choice(WordList)
NumberOfLetters = len(Word)
print("There are", NumberOfLetters, "letters in the word.")
for i in range (NumberOfLetters):
print("Guess a letter:")
LetterGuess = input()
LetterList.append(LetterGuess)
if LetterGuess in LetterList:
print("You already guessed that letter")
elif LetterGuess in Word:
print("Correct")
print("You now have the correct letters: ", LetterList)
i += 1
elif LetterGuess not in Word:
print("Wrong")
print("You have the correct letters: ", LetterList)
When i guess a number it says this:
---Hangman---
There are 11 letters in the word.
Guess a letter:
d
You already guessed that letter
You add the guess to the list, then immediately check whether it is there.
LetterList.append(LetterGuess)
if LetterGuess in LetterList:
Here is my code:
import random
guesses = 0 #Number of tries to guess.
print ("Welcome to Guess Me!")
print ("\nYou have five guesses, choose letter and guess a word.")
print("\nAll of luck!")
def rand_word():
f = open('sowpods.txt', 'r').readlines() #Sowpods is library with some random words
return random.choice(f).strip()
word = rand_word()
print word #I printed a word just so i can test if is working.
correct = word
lenght = len(word) #I want to tell them how many letters a word contain
new_length = str(lenght)
guess = raw_input("The word is " + new_length + " letters long. Guess a letter: ")
while guesses < 5:
if guess not in word:
print("Sorry, this letter is not in word.")
else:
print("Correct, word contain this letter!")
guesses =+ 1
if guesses > 5:
final_answer = raw_input("You ran out of guesses, what is your answer?")
if final_answer == correct:
print("That's correct, congratulations you won!")
else:
print("Sorry, correct word is" + " " + word + " ,you can try again!")
Problem is when i run my code, and let's say i type letter "s", my sublime freeze and i get message "Sublime 3 is not responding.." and i have to turn it off. Maybe it's while loop? Infinite?
There are a few things.
guesses =+ 1 should be guesses += 1 and at the top of the while loop before any if statements
I think your guess = raw_input should be within the while loop before any of the if statements. So it will keep asking and counting for each guess until it reaches 5. The last if statement within the loop should be if guesses == 5 or guesses >= 5 instead of guesses > 5.
Mostly just reordering things all within the while loop. Everything under the code within the while loop will be ran for every guess.
I changed it according to the above and it works great for me:
while guesses < 5:
guesses += 1
guess = raw_input("The word is " + new_length + " letters long. Guess a letter: ")
if guess not in word:
print("Sorry, this letter is not in word.")
else:
print("Correct, word contain this letter!")
if guesses == 5:
final_answer = raw_input("You ran out of guesses, what is your answer?")
if final_answer == correct:
print("That's correct, congratulations you won!")
else:
print("Sorry, correct word is" + " " + word + " ,you can try again!")
Welcome to Guess Me!
You have five guesses, choose letter and guess a word.
All of luck!
word
The word is 4 letters long. Guess a letter: 1
Sorry, this letter is not in word.
The word is 4 letters long. Guess a letter: 2
Sorry, this letter is not in word.
The word is 4 letters long. Guess a letter: 3
Sorry, this letter is not in word.
The word is 4 letters long. Guess a letter: 4
Sorry, this letter is not in word.
The word is 4 letters long. Guess a letter: 5
Sorry, this letter is not in word.
You ran out of guesses, what is your answer?numbers
Sorry, correct word is word ,you can try again!
You have an infinite loop because your 'guesses' variable is not being inceremented in the while loop; move the 'guesses += 1' into the loop itself e.g.
while guesses < 5:
if guess not in word:
print("Sorry, this letter is not in word.")
else:
print("Correct, word contain this letter!")
guesses += 1
I'm new to python and have been working through a book. At the end of the chapter there was a challenge to create a game where the computer picks a random word and the player has to guess that word. The computer tells the player how many letters are in the word. The player gets five chances to ask if the letter is in the word. The computer responds with only a yes/no. The player then has to guess the word. Here is my attempt at this:
print ("\t\t\tWelcome to the guess my word challenge")
print ("\nThe computer will pick and random word and you have to guess it in five tries")
import random
#create sequence of words
WORDS = ("computer","laptop","mouse","keyboard")
#pick random word
word=random.choice(WORDS)
correct=word
tries=0
print ("This word has ",len(word), "letters")
i=""
while word != "" and tries<5:
for i in word:
i=input("Guess a letter: ")
if i not in word:
print ("No")
else:
print ("\nYes")
tries+=1
if tries==5:
print("You've run out of tries")
final=input("\nGuess my word: ")
if word==correct:
print ("Well done that was my word!")
else:
print ("Better luck next time")
input ("\n\nPress the enter key to exit")
Now the problem I'm having is I can't get the tries bit to work, eventually the program will say you've run out of tries but I want it to say that after 5 tries. Also, no matter what word I put in at "guess my word", it always displays its correct even if it isn't.
There are two problems with your code.
You ask the user for a letter for each letter in the word, and only then increment the tries counter, then ask again for each letter in the word. Remove the for i in word: loop.
You compare the word to correct, which is just the word itself. Instead, you have to compare it to the user's final guess, i.e. if word==final:
With those two fixes, it should work.
You want to count down the number of times the player guesses. The for loop
for i in word:
will cycle one time for each letter in the word, setting i equal to that letter, but you then reassign i to user input. So if you remove the for loop, it should run as intended.
i=""
while word != "" and tries<5:
i=input("Guess a letter: ")
if i not in word:
print ("No")
else:
print ("\nYes")
tries+=1
if tries==5:
print("You've run out of tries")
[EDIT] Also you're not comparing the correct word to the user input, so you want to say
if correct == final :
import random
word = random.choice(['computer','laptop','mouse','keyboard'])
def guess(tries = 0):
letter = input('Guess a letter: ')
if letter in word:
print('\nYes')
else:
print('No')
tries += 1
if tries == 5:
return
guess(tries)
print('\t\t\tWelcome to the guess my word challenge')
print('\nThe computer will pick and random word and you have to guess it in five tries')
print('This word has {0} letters'.format(len(word)))
guess()
final = input('\nGuess my word: ')
if final == word:
print('Well done that was my word!')
else:
print('Better luck next time')
input('\n\nPress the enter key to exit')
So my program is this so far:
def update():
print word
counter = 0
blanks = len(word)*'-'
blank_list = list(blanks)
letter = raw_input('Please enter a single letter: ')
for index in range(len(word)):
if letter in word[index]:
blank_list[index] = letter
print ''.join(blank_list)
letter = raw_input('Please enter a single letter: ')
but when I enter a correct letter in the wrong order it displays it as an incorrect guess, ie, one of my words is horse, if i entered an o it would display -o---, but if I entered an h, it would come up as None, because haven't set parameters of what to do when it is incorrect guess. This goes for when it is if letter in word[index] or if letter == word[index].
any suggestions on how to fix this problem?
Here, you enforce order by looking at the exact index:
if letter == word[index]
You want to ask if letter in word. You can also find the exact index of the letter with word.index(letter) (careful with repeated letters).
I think the problem is that you have a for loop based on index so when you enter a correct answer the next correct letter has to be in a later index because you already passed the previous indexes. For a hangman program I might do something with a while loop and use a count like you have and if the count exceeds your limit then break the while loop and make you word a list of letters. Then check to see if your guessed letter is within your list of letters of the word.
so if your guess limit is 5 then do something like
break word into list
set guess count to 0
while guess_count < 5:
if letter in word_list:
#update
else:
guess_count += 1
The problem is that your guesses are based on indexing. Once you guess a letter, you cannot guess one before that.
Running your code:
>>> update('mouse')
mouse
Please enter a single letter: m
m----
Please enter a single letter: u
m-u--
Please enter a single letter: o
>>>
It exits because the placing of 'u' is after that of 'o'. Instead change your code to this:
def update(word):
found = False
guesses_left = 3
blank_list = list(len(word)*'_')
while guesses_left > 0:
letter = raw_input('Enter your letter: ')
for k in range(len(word)):
if word[k] == letter and letter not in blank_list:
blank_list[k] = letter
found = True
if found == False:
guesses_left-=1
else:
found = False
print ''.join(blank_list)
if '_' not in blank_list:
break
if guesses_left < 1:
print 'You lost!'
else:
print 'You won!'
Running my code:
>>> update('mouse')
Enter your letter: m
m____
Enter your letter: s
m__s_
Enter your letter: u
m_us_
Enter your letter: o
mous_
Enter your letter: e
mouse
You won!
>>>