I am attempting to make a 'simple' hangman game in python, but this if statement seems to not believe answer is == to guess, even when it clearly is... Thanks for any help :)
import random
guessed = False
file = open("hangmanwords.txt")
answer = file.readlines()[random.randint(0, 212)]
print(answer)
print("_ "*(len(answer)-1),"\n")
for counter in range(0,6):
guess = input("Enter your guess:\n")
if guess == answer:
break
else:
print("Unlucky, try again")
if counter == 5:
print("Unlucky, you did not guess it correctly. The correct word was",answer)
else:
print("Well done, you got it!")
The lines returned by readlines end in a newline (except, potentially, the last line).
In your case, you don't want that. You can use str.strip() to remove whitespace (including newlines) from the beginning and end of a string.
You can also use random.choice to select a random word. Which is useful if you later want to add or remove words without changing the code!
Also, you don't need to hardcode the number of tries if you use the for-else construct.
import random
with open("hangmanwords.txt") as file:
answer = random.choice([line.strip() for line in file if line and not line.isspace()])
print(answer)
print("_ " * len(answer))
for counter in range(6):
guess = input("Enter your guess:\n")
if guess == answer:
print("Well done, you got it!")
break
else:
print("Unlucky, try again")
else:
print("Unlucky, you did not guess it correctly. The correct word was", answer)
Related
I'm currently learning Python and trying to build a set of minigames to solidify my basic knowledge, however there are a few things I want to do with my game that others on here haven't (from what I've seen, at least), and that is remove whitespace between words from the answer and the "masked" answer. I assume it would be done as an "if, else" sort of statement? Please correct me if I'm wrong.
for x in range(i): ## where i is the word
if x == " ":
continue ## wouldn't it be pointless to append something that you don't want to change?
else:
word.append('_')
Another question I had was regarding a loop statement I have at the beginning of my game, within this loop I have an if/else stating that if there are more than 1 letter in the guess, it'll return a statement telling the user that's not valid. But the game immediately stops working afterword.
while guesses < 6:
guess = raw_input("Please guess a letter: ")
if len(guess) > 1:
return "One letter at a time!"
else: continue
I'm not quite sure what to add to my code to make it continue asking for input after this.
Here's my full code, it's currently not working for me after asking for input... I took the code it from another user on here and fixed it to my tastes, since their game didn't use more than one word and didn't check to see if there was more than one letter being input when prompted, and I figured it would be good practice to modify existing code to make it do a bit more than it originally does.
def hangman():
guesses = 0
word = []
guessed = []
words = ["bichon frise", "maltese", "dachshund", "pomeranian", "golden retriever", "shih tzu", "rottweiler", "pit bull", "beagle", "poodle", "akita", "basset hound", "border collie", "boston terrier", "boxer", "bulldog", "chow chow", "chihuahua", "chinese crested", "french bulldog", "great dane", "great pyrenees", "greyhound", "icelandic sheepdog", "irish wolfhound", "komondor", "mastiff", "shnauzer", "pekingese", "welsh corgi", "redhound coonhound", "samoyed", "shiba inu", "weimaraner", "whippet", "italian greyhound", "yorkshire terrier"]
print "Welcome to Hangman. The words chosen are the names of various breeds of dogs, try and guess the word before the man is hung!"
answer = random.choice(words)
i = len(answer)
print "The length of the word is", i, "characters long"
for x in range(i):
if x == " ":
continue
else:
word.append('_')
while guesses < 6:
guess = raw_input("Please guess a letter: ")
if len(guess) > 1:
return "One letter at a time!"
else:
continue
if (guess in i):
print "The letter is in the word."
for index, letter in enumerate(i):
if letter == guess:
word[index] = guess
guessed.append(guess)
else:
print "The letter is not in the word"
guesses = guesses + 1
guessed.append(guess)
print "You have guessed these letters so far: %s)" % (''.join(guessed))
print "Letters matched so far %s): %" (''.join(word))
if ''.join(word) == answer:
break
if guesses == 6:
print "You didn't guess the right answer in time! The answer was %s" % answer
else:
print "You guessed the word!"
remove whitespace between words from the answer.
Given i (i as a string?) is the string, you probably should not use range(..) on it since range expects an int. Furthermore why do you build a list instead of a new string? You can however easily use a generator:
word = ''.join(c for c in i if c != ' ')
word is here a string that contains all characters of i that are not ' '. If you want however to generate a sequence of underscores, you can use:
word = ''.join('_' for c in i if c != ' ')
If you want to construct a list (which the remainder of the code expects), you can use list comprehension:
word = ['_' for c in i if c != ' ']
it'll return a statement telling the user that's not valid. But the game immediately stops working afterword (sic.).
That's because you use a return statement: return means you jump out of the function and (optionally) return a value. You probably want to print(..):
guesses = 0
while guesses < 6:
guess = raw_input("Please guess a letter: ")
if len(guess) > 1:
print("One letter at a time!")
else:
#process char
continue
I also noticed you use continue. continue means that you abandon the remainder of the iteration and take the next one, so it means you will not process the query. So you have to remove the continue part:
while guesses < 6:
guess = raw_input("Please guess a letter: ")
if len(guess) > 1:
print("One letter at a time!")
return ends the function right there, use print instead:
print "One letter at a time!"
As for the whitespace, why don't you append the space to the masked word? That way, the player won't have to guess it, can see that there are spaces, and your join-check will work:
for x in range(i):
if x == " ":
word.append(' ')
else:
word.append('_')
How would I go about telling the user when they've got the correct letter in a list? Only way I know of is to insert the index, but that doesn't feel very flexible, especially when the words vary in length.
import random
possibleWords = [["apple"], ["grapefruit"], ["pear"]]
randomWord = random.choice(possibleWords)
anotherWord = ''.join(randomWord)
finalWord = list(anotherWord)
maxTries = list(range(0, 11))
attemptsMade = 0
triesLeft = 10
print("Hangman!")
print("\nYou got {} tries before he dies!".format(maxTries[10]))
print("There's {} possible letters.".format(len(finalWord)))
for tries in maxTries:
userChoice = input("> ")
if userChoice == finalWord[0]:
print("You got the first letter correct! It is {}.".format(finalWord[0]))
else:
print("Ouch! Wrong letter! {} tries remaining.".format(triesLeft))
attemptsMade += 1
triesLeft -= 1
Talking about characters in lists, or - what i think is more likely in your case - chars in words you can just check for
if userChoice in finalWord:
# [...] do stuff here
and further on use the index function to determine the position (or positions if multiple occurence).
finalWord.index(userChoice)
You could sure also go the way using index() function directly and work your way using the return values.
Use Python's "in" keyword to check if something is within a list/iterable.
if userChoice in finalWord:
Though for this, I'd just use regex or list comprehension to get the indexes while you are at it, since you might want them for the game.
char_indexes = [i for (i, l) in enumerate(finalWord) if l == userChoice]
if len(char_indexes):
Use a set for the letters that are in the word, and whenever the player guesses a letter, check if the letter is still in the set. If it’s not, it was a wrong letter; if it is, then remove that letter and just continue. If the set is empty at some point, then the player guessed all letters of the word.
Something to get you started:
def hangman (word):
letters = set(word.lower())
attempts = 5
while attempts > 0:
guess = input('Guess a character ')
if guess[0].lower() in letters:
print('That was correct!')
letters.remove(guess[0])
else:
print('That was not correct!')
attempts -= 1
if not letters:
print('You solved the word:', word)
return
hangman('grapefruit')
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"
I need to find a way to check if my randomly generated answer is the same as the user input and then track the number of rights and wrongs. heres what I have
import random
def playerTriviaQuestions():
fo = open("playerstriviaquestions.csv","r")
players = fo.readlines()
rquestions = random.choice(players)
data = rquestions.split(",")
rquestions = data[0]
answer = data[1]
print(rquestions)
print("")
print(answer)
guess = input("Answer: ")
if guess == answer:
print("Correct")
else:
print("Wrong")
fo.close()
You should use raw_input("Answer: ") to ensure the type you are comparing the answer to is a string (in python 2).
As far as I can tell everything else in your code should work. You may want to use:
if guess.lower().strip() == answer.lower().strip():
So that it is not case-sensitive and so that leading and trailing whitespace is removed.
LETTERS = "abc"
correct = "cab "
guess = ""
while guess != correct:
for i in LETTERS:
position = random.randrange(len(LETTERS))
guess += LETTERS[position]
LETTERS = LETTERS[:position] + LETTERS[(position + 1):]
print(guess)
I'm new in Python and I want to make this simple program:
With the letters "abc", jumble them and create a new three-lettter word randomly.
Print that jumble
Continue doing this loop until the computer jumbles "cab".
Then stop.
I came up with this code, and it gives me an infinite loop. I can't figure out why is doing it. I'm sure it's something easy but I can't see it. Need some help! Thanks!
You have three problems that I can see:
"cab " has a space in it, and LETTERS does not have a space. So you'll never be able to guess a space
You don't reset guess. You simply keep adding to it
You change LETTERS in your for-loop, so in the second iteration of your while-loop, it will be completely empty.
This is how I would go about doing what you're trying to do (with minimal modification):
_LETTERS = "abc"
correct = "cab"
guess = ""
while guess != correct:
LETTERS = _LETTERS[:]
guess = ""
for i in LETTERS:
position = random.randrange(len(LETTERS))
guess += LETTERS[position]
LETTERS = LETTERS[:position] + LETTERS[(position + 1):]
print(guess)
Here's how I would do a random search (which is what you're trying to do):
guess = "abc"
correct = "cab"
while guess != correct:
guess = list(guess)
random.shuffle(guess)
guess = ''.join(guess)
print(guess)
print(guess)
Of course, there are better techniques to correctly guess "cab". If you really want to try an exhaustive search, then you could use a backtracking DFS:
def DFS(letters, correct, sofar=None)
if sofar is None:
sofar = ''
if not letters:
if sofar == correct:
print("Yay! I found it")
else:
print("Oops! I found %s instead" %sofar)
else:
for i,char in enumerate(letters):
DFS(letters[:i]+letters[i+1:], correct, sofar+char)
Your correct value contains a space, but your loop never generates spaces:
correct = "cab "
Remove that space:
correct = "cab"
Next, your loop reduces LETTERS to an empty string, so only once does your loop produce a random guess, but afterwards, you forever are stuck with LETTERS = '', so no for loop is run.
You'd be better off using random.shuffle to produce guesses:
LETTERS = list("abc")
correct = "cab"
while True:
random.shuffle(LETTERS)
guess = ''.join(LETTERS)
if guess == correct:
print(guess)
break