Python hangman game for loop - python

When I guess the letter it keeps applying the letter. for example
say the word is words, then I would guess the letter d, then it would do
ddddd. it uses that letter for the whole word. here is my code.
import random
print(" Welcome to the HangMan game!!\n","You will have six guesses to get the answer correct, or you will loose!!!",)
lines = open("../WordsForGames.txt").read()
line = lines[0:]
#lines 24-28 Randomly generate a word from a text file
words = line.split()
myword = random.choice(words)
print(myword)
words = myword
fake = '_'*len(myword)
count = 0
print(fake)
guesses = 0
guess = input("Enter a letter you would like to guess: ")
fake = list(fake) #This will convert fake to a list, so that we can access and change it.
for re in range(0, len(myword)):#For statement to loop over the answer (not really over the answer, but the numerical index of the answer)
fake[re] = guess #change the fake to represent that, EACH TIME IT OCCURS
print(''.join(fake))
if guess != (''.join(fake)):
print("The letter ", guess,"was in the word. Guess another letter please!")
guess = input("Enter another letter you would like to guess: ")
fake[re] = guess #change the fake to represent that, EACH TIME IT OCCURS
print(''.join(fake))

This part is the culprit:
for re in range(0, len(myword)):#For statement to loop over the answer (not really over the answer, but the numerical index of the answer)
fake[re] = guess #change the fake to represent that, EACH TIME IT OCCURS
print(''.join(fake))
This code replace every element in fake with guess

Related

Why is this loop not working, also how do I make the code remember the previous letters guessed?

Im new to programming and was trying to program a word guesser. I dont understand why the while loop doesnt go though three times, also the program doesnt remember the previously guessed letters.
import random
words = ["hello", "bye", "petscop"]
GuessWord = random.choice(words)
tries = 3
while tries > 0:
tries = tries - 1
inp = input("\nEnter your guess: ")
for char in GuessWord:
if char in inp:
print(char, sep="",end="")
elif char not in inp:
print("_", sep="",end="")
tries = tries - 1
I'm sorry to say, StackOverflow isn't a forum for debugging. StackOverflow is more about solving general problems that affect multiple people rather than single instances of a problem (like bugs), if that makes sense.
There is probably a better place for you to ask this question but I can't think of one off the top of my head.
In the spirit of being constructive: the following code appears twice and you should remove the second instance.
tries = tries - 1
Also, you are overwriting inp each time you enter the loop causing it to forget its previous value. There are other issues too. But that's a good start.
The main problem you have is that you decrease the number of tries by 2 each round. Therefore, at the beginning of the second round, the number of tries decreases again so it fails. This is how I would do it:
import random
# library that we use in order to choose
# on random words from a list of words
name = input("What is your name? ")
# Here the user is asked to enter the name first
print("Good Luck ! ", name)
words = ['rainbow', 'computer', 'science', 'programming',
'python', 'mathematics', 'player', 'condition',
'reverse', 'water', 'board']
# Function will choose one random
# word from this list of words
word = random.choice(words)
print("Guess the characters")
guesses = ''
# any number of turns can be used here
turns = 3
while turns > 0:
# counts the number of times a user fails
failed = 0
# all characters from the input
# word taking one at a time.
for char in word:
# comparing that character with
# the character in guesses
if char in guesses:
print(char)
else:
print("_")
# for every failure 1 will be
# incremented in failure
failed += 1
if failed == 0:
# user will win the game if failure is 0
# and 'You Win' will be given as output
print("You Win")
# this print the correct word
print("The word is: ", word)
break
# if user has input the wrong alphabet then
# it will ask user to enter another alphabet
guess = input("guess a character:")
# every input character will be stored in guesses
guesses += guess
# check input with the character in word
if guess not in word:
turns -= 1
# if the character doesn’t match the word
# then “Wrong” will be given as output
print("Wrong")
# this will print the number of
# turns left for the user
print("You have", + turns, 'more guesses')
if turns == 0:
print("You Loose")

How to reveal a specific letter in a string for Python?

I am in high school and am currently teaching myself Python. I am programming Hangman and it is going well so far (it is not very organized yet) but I am having a problem. I created a list of words that I would use for the game and replaced them with asterisks using the range function. Here is the code for that:
words = ['utopia', 'prosecute', 'delirious', 'superficial', 'fowl', 'abhorrent', 'divergent',
'noxious', 'scarce','lavish', 'hinder', 'onerous', 'colossal', 'infringe']
picked_words = random.choice(words)
for i in range(len(picked_words)):
print(picked_words.replace(picked_words,'*'), end = '')
I am at the point where I am guessing the letters and I need to slowly reveal the position of certain letters. I have tried looking for certain functions (I even thought that the find() function would work since it prints the location of a letter in a string but it did not) and I am at a loss. Especially for words with multiples of the same letter such as "onerous" and "infringe." I will write the code that I have so far for this section:
def right_letter(correct):
if correct == True:
print("There are {} {}'s.".format(number_of_char, guess))
for x in range(len(picked_words)):
print(picked_words.replace(picked_words,guess, #find way to fill in specific letters),end = '')
I have no clue what parts of the code are necessary to get an answer but my code is really unorganized because I do not know proper techniques yet. The portion that says for x in range(len(picked_words))... is where I am having trouble. The rest of the code ran fine before I added the print statement underneath it. Basically I am asking how to change a certain character or specific characters and put them where they belong. For example, if the randomized word was "infringe" and the first guess was "i" how do I go from ******** to i***i***?
Also, in case anyone was wondering what I originally thought the solution was...
picked_words[(picked_words.find(guess))]
I thought that it would simplify and become picked_words[index]
Here's an example of converting your code to the hangman game.
Note how variable display in the code is updated to show user the correct guessed letters.
import random
def hangman():
words = ['utopia', 'prosecute', 'delirious', 'superficial', 'fowl', 'abhorrent', 'divergent',
'noxious', 'scarce','lavish', 'hinder', 'onerous', 'colossal', 'infringe']
max_guesses = 5
word = random.choice(words)
guesses = 0
display = "*" * len(word)
print(display, " Is the word")
while guesses < max_guesses:
letter = input("Please Enter Your guess letter: ")
if letter.lower() not in word:
guesses += 1
print("You got it incorrect, you have: ", max_guesses - guesses , " Additional trials")
else:
print("Right guess!")
new_display = ''
for w, l in zip(word, display):
if letter.lower() == w:
new_display += letter.lower()
else:
new_display += l
display = new_display
print(display)
if not '*' in display:
print("You won!")
return
hangman()
Basically you will need to find a partial match between your letter and the word here.
The easiest way i can think of is Pythons in Operator. It can be used like this
if picked_letter in picked words
% here you need to figure out at which position(s) the letter in your word occurs
% and then replace the * at the correct positions. A nice way to do this is
% the use of regular expressions
picked_words = re.sub('[^[^picked_letter]*$]', '*', picked_words)
%this will replace every letter in your word with the Asterisk except for the one picked
else
%do Nothing
Note that running this Code in a loop would replace every character in your string except the picked one EVERY time., therefore it is probably best to design your picked_letter as a list containing all characters that have been picked so far. This also makes it easier to check wether a letter has already been entered.

Coding Hangman in Python

I'm having trouble with this hangman coding. When I run the code, it asks the question "Type in a letter a - z", but when I type in a letter, instead of it putting a letter, it just ask the same question from the beginning without letting me know if the letter is correct or not.
import random
possibleAnswers = ["page","computer","cookie","phishing","motherboard","freeware","bus","unix","document","hypertext","node","digital","worm","macro","binary","podcast","paste","virus","toolbar","browser"]
random.shuffle(possibleAnswers)
answers = list(possibleAnswers[1])
display = []
display.extend(answers)
for i in range(len(display)):
display[i] = "_"
print ' '.join(display)
print "\n\n\n\n"
count = 0
while count < len(answers):
guess = raw_input("Type in a letter a - z: ")
guess = guess.upper()
for i in range(len(answers)):
if answers[i] == guess:
display[i] = guess
count += 1
print ' '.join(display)
print "\n\n\n"
It does tell you, after a fashion. The problem is that your entire word list is lower-case, but you specifically change all of your input guesses to upper-case. Those cannot match, so there's never a "correct" guess. Change the word list to capitals, or change your conversion from upper to lower.

python if answer is correct display a well done message?

I'm trying to set a memory word game where the program reads a text file with 10 words. The program reads the file and creates a list of 9 out of the words .pop() the last word no.10. The words are randomly shuffled and then displayed again with a 2nd list of the same words randomly shuffled with the last word .pop() and the 1st removed is replacing the word (removed / substituted) - hope that sort of explains it.
I an having an issue regarding feeding back the right response whenter code hereen the user guesses the correct answer (it nots) everything else appears to be working.
import time
from random import shuffle
file =open('Words.txt', 'r')
word_list = file.readlines()
word_list [0:9]
shuffle(word_list)
extra_word=(word_list.pop())
print (extra_word)#substitute word for 2nd question (delete this line)
print '...............'
print (word_list)
print ('wait and now see the new list')
time.sleep(3)
print ('new lists')
word_list [0:9]
shuffle(word_list)
newExtra_word=(word_list.pop())
print (newExtra_word)#replace word for 1st question (delete this line)
word_list.insert(9,extra_word)# replace word
print (word_list)
This code above works fine (for what i want it to do..) The section below however:
#ALLOW FOR 3 GUESSES
user_answer = (raw_input('can you guess the replaced word: ')).lower()
count = 0
while count <=1:
if user_answer == newExtra_word:
print("well done")
break
else:
user_answer = (raw_input('please guess again: ')).lower()
count+=1
else:
print ('Fail, the answer is' + extra_word)
The code does allow for three guesses, but will not accept the removed list item. Does anyone have any ideas why?
Well, because your code above DOESN'T work the way you want it to.
file = open('Words.txt', 'r')
word_list = file.readlines()
# you should do file.close() here
word_list[0:9]
That last line doesn't actually do anything. It returns the first 10 elements in word_list but you never assign them to anything, so it's essentially a NOP. Instead do
word_list = word_list[0:9] # now you've removed the extras.
Probably better is to shuffle first so you have a truly random set of 10. Why 10? Why are we restricting the data? Oh well, okay...
# skipping down a good ways
word_list.insert(9, extra_word) # replace word
Why are we doing this? I don't really understand what this operation is supposed to do.
As for allowing three guesses:
count = 0
while count < 3:
user_answer = raw_input("Can you guess the replaced word: ").lower()
count += 1
if user_answer == newExtra_word:
print("well done")
break
else:
print("Sorry, the answer is " + extra_word)
Wait, did you catch that? You're checking the user input against newExtra_word then you're reporting the correct answer as extra_word. Are you sure your code logic works?
What it SOUNDS like you want to do is this:
with open("Words.txt") as inf:
word_list = [next(inf).strip().lower() for _ in range(11)]
# pull the first _11_ lines from Words.txt, because we're
# going to pop one of them.
word_going_in = word_list.pop()
random.shuffle(word_list)
print ' '.join(word_list)
random.shuffle(word_list)
word_coming_out = word_list.pop()
# I could do word_list.pop(random.randint(0,9)) but this
# maintains your implementation
word_list.append(word_going_in)
random.shuffle(word_list)
count = 0
while count < 3:
user_input = raw_input("Which word got replaced? ").lower()
count += 1
if user_input == word_coming_out:
print "Well done"
break
else:
print "You lose"

python improving word game

Im working on a word game. The purpose for the user is to guess a 5 letter word in 5 attempts. The user can know the first letter. And if he doesn't get the word correct, but if he has a letter in the correct place he gets to know this.
This is my code:
import random
list_of_words = ["apple","table", "words", "beers", "plural", "hands"]
word = random.choice(list_of_words)
attempts = 5
for attempt in range(attempts):
if attempt == 0:
tempList = list(word[0] + ("." * 4))
print("The first letter of the word we are looking for: %s" % "".join(tempList))
answer = raw_input("What is the word we are looking for?:")
if len(answer) != 5:
print ('Please enter a 5 letter word')
Else:
if answer != word:
wordlist = list(word)
answerlist = list(answer)
for i in range(min(len(wordlist), len(answerlist))):
if wordlist[i] == answerlist[i]:
tempList[i] = wordlist[i]
print(tempList)
else:
print("correct, you have guessed the word in:", attempt, "attempts")
if answer != word:
print("Sorry maximum number of tries, the word is: %s" % word)
I have two questions about this code:
The first one is a small problem: If the user gives a 6 or 4 letter word it will still print the word. While I'd rather have it that the word is just ignored and the attempt isnt used..
If a letter is given correct (and also the first letter) it doesnt become a standard part of the feedback. Trying to get this with temp but of yet its not working great.
Any suggestions to clean up my code are also appreciated!
Thanks for your attention
I made some changes in your code, now it's working according to your specification. I also wrote a couple of explaining comments in it:
import random
list_of_words = ["apple", "table", "words", "beers", "plural", "hands"]
word = random.choice(list_of_words)
# changed the loop to a 'while', because i don't want to count the invalid length answers
# and wanted to exit the loop, when the user guessed correctly
attempts = 5
attempt = 0
correct = False
while attempt < attempts and not correct:
if attempt == 0:
# i stored a working copy of the initial hint (ex: "w....")
# i'll use this to store the previously correctrly guessed letters
tempList = list(word[0] + ("." * 4))
print("The first letter of the word we are looking for: %s" % "".join(tempList))
answer = raw_input("What is the word we are looking for?:")
if len(answer) != 5:
print("Please enter a 5 letter word")
else:
if answer != word:
# i simplified this loop to comparing the wordlist and answerlist and update templist accordingly
wordlist = list(word)
answerlist = list(answer)
for i in range(min(len(wordlist), len(answerlist))):
if wordlist[i] == answerlist[i]:
tempList[i] = wordlist[i]
print(tempList)
else:
correct = True
print("Correct, you have guessed the word in %s attempts" % (attempt + 1))
attempt += 1
if answer != word:
# also i used string formatting on your prints, so is prints as a string, and not as a tuple.
print("Sorry maximum number of tries, the word is: %s" % word)
There are several problems with the code.
Just 1 for now. I notice in the sample output you are entering five letter words (beeds and bread) and it still prints out Please enter a 5 letter word.
These two lines:
if len(answer) != 4:
print ('Please enter a 5 letter word')
Surely this should be:
if len(answer) != 5:
print ('Please enter a 5 letter word')
continue
This would catch an invalid input and go round the loop again.
Answering your specific questions:
You will need to have a for loop around your input, keeping the user in that loop until they enter a word of appropriate length
If you move guessed letters to the correct places, it is trivial to win by guessing "abcde" then "fghij", etc. You need to think carefully about what your rules will be; you could have a separate list of "letters in the guess that are in the answer but in the wrong place" and show the user this.
To keep the display version with all previously-guessed characters, keep a list of the display characters: display = ["." for letter in answer], and update this as you go.
Other problems you have:
Too much hard-coding of word length (especially as len("plural") != 5); you should rewrite your code to use the length of the word (this makes it more flexible).
You only tell the user they've won if they guess the whole answer. What if they get to it with overlapping letters? You could test as if all(letter != "." for letter in display): to see if they have got to the answer that way.
Your list comprehension [i for i in answer if answer in word] is never assigned to anything.

Categories