Python: Hangman game problems - python

I am brand new to Python but a have a littel Matlab and C++ background. Please Help!!!!
I am having problems with my hangman code. If a word has multiple of the same letter in I cannot figure out how to get it to switch all of them. I have a couple tries with some of them commented out.
import random
import time
import sys
def pickWord():
words = [line.strip() for line in open('word_list.txt')]
word = random.choice(words)
word = word.lower()
return word
def checkLetter(word, input):
if input not in word:
in_letter = 0
else:
in_letter = 1
return in_letter
def check_input(input):
if input.isaplha() == False :
input = raw_input('Your input was not a letter, please enter a letter: ')
elif len(input) > 0:
input = raw_input('Your entry was longer than 1 letter, please enter one letter: ')
else:
input = input
return input
#main function
running = 'y'
print('Lets Play Hangman!\n\n ------------------------ \n\nGenerating a Random word \n\n')
while running == 'y':
word = pickWord()
letters = list(word)
time.sleep(3)
print ('The word has been chosen\n\n')
print '%s' % word
start = raw_input('Are you ready to start?(y/n)')
start = start.lower()
if start == 'n':
print('Well, too damn bad. Here We go!\n\n **************************\n\n')
elif start == 'y':
print('Awesome, lets begin!\n\n*********************************\n\n')
else:
print('You did not enter y or n, sorry you are not allowed to play!')
sys.exit()
i = 0
print ('The word has %d letters in it') % len(word)
input = raw_input('What is your first guess: ')
input = input.lower()
correct = ['_'] * len(word)
print ' '.join(correct)
while correct != letters and i <= 5:
'''if input in letters:
for input in letters:
location = letters.index(input)
correct[location] = input
print('You guessed the correct letter! Your input %s is in the word at the %d spot.') % (input, location)
print ' '.join(correct)
elif input not in letters:
print('You guessed wrong :(')
i = i + 1
guesses = 6 - i
print('You have %d guesses left.') % guesses
guesses = 0
else:
print('You did not enter a valid letter, please try again.')'''
'''for j in letters:
if j == input:
location = letters.index(j)
correct[location] = j
print '%s' % ' '.join(correct)
print '%d' % location
print '%s' % j
if j == input:
location = letters.index(j)
correct[location] = j
print('You guessed the correct letter! Your input %s is in the word at the %d spot.') % (input, location)
print ' '.join(correct)'''
if input not in letters:
i = i + 1
guesses = 6 - i
print("You guessed incorrectly. You have %d guesses left.") % guesses
input = raw_input('What is your next guess: ')
input = input.lower()
if correct == letters:
print('Congrats! You won the game!')
else:
print('You lost. :(')
running = raw_input('Do you want to play again? (y/n)').lower()

In your attempt, the loop is stopping when it finds the first match of input to letters.
the following code will work:
guess = raw_input('What is your first guess: ')
word = "wordword"
letters = list(word)
correct = ['_']* len(word)
for x, y in enumerate(word):
if guess == y:
correct[x] = y
Your mistakes
In your first attempt:
if input in letters:
for input in letters:
you are checking if input is in letters, which is fine, but if this returns True, inputs original value is lost, and is reassigned as you loop through the elements of letters.
eg
>>>input = "w"
>>>word = "word"
>>>if input in word:
... for input in word:
... print(input)
w
o
r
d
your second attempt
for j in letters:
if j == input:
location = letters.index(j)
is a lot closer to being successful, however location = letters.index(j) is always going to equal the index of the first match of j, and thus will not assign all matched values of input.

Related

Was isn't the "g" being displayed in the output when it is entered again

Output
word = input("Enter a word: ").lower()
corrects = len(word)
players_word = "_"*len(word)
tries = 6
word_list = list(word)
for i in range(6+len(word)):
print(players_word)
guess = input("Enter your {} guess: ".format(i+1)).lower()
if guess in word_list:
corrects -= 1
print("Correct !!!")
players_word = list(players_word)
players_word[word.find(guess)] = guess
word_list.remove(guess)
if corrects == 0:
print("Congratulation, you won.".title())
breaka
else:
print("Wrong")
tries -= 1
print("You have {} tries remaining".format(tries))
if tries == 0:
print("Lost")
break
The error occurs for a word with a character occurring multiple times. For example, in the given picture the "g" is not being displayed in the output when it is entered again.
your word.find(guess) is always going to be locating the first occurrence of that letter within the word. You'll need to find a way to find the next occurence of that letter, if the word.find(guess) != "_".
word = input("Enter a word: ").lower()
corrects = len(word)
players_word = "_"*len(word)
tries = 6
word_list = list(word)
for i in range(6+len(word)):
print(players_word)
guess = input("Enter your {} guess: ".format(i+1)).lower()
if guess in word_list:
corrects -= 1
print("Correct !!!")
players_word = list(players_word)
for i in range(len(players_word)):
if players_word[word.replace(guess, '~', i).find(guess)] == '_':
players_word[word.replace(guess, '~', i).find(guess)] = guess
break
word_list.remove(guess)
if corrects == 0:
print("Congratulation, you won.".title())
break
else:
print("Wrong")
tries -= 1
print("You have {} tries remaining".format(tries))
if tries == 0:
print("Lost")
break

How terminate this loop after a a given number of attempts?

For the most part it seems to be working, but not how I'm trying to get it to work. When I run it I am allowed unlimited tries to guess every single letter in the word until I spell out the word.
But that's not what I am going for, I'm trying to give the users 5 guesses with single letters if the letter is in the word then it will tell them "Yes", there is a(n) (users guess) in my word, but if the letter is not in my word then it will tell them "No", there is not a(n) (users guess) in my word.
After 5 attempt's at guessing different letters I want them to have to guess the full word but I can't figure out how.
This is what I have now:
import random
def get_word():
words = ['cat', 'dog', 'man', 'fox', 'jar']
return random.choice(words).upper()
def check(word,guesses,guess):
status = ''
matches = 0
for letter in word:
if letter in guesses:
status += letter
else:
status += '*'
if letter == guess:
matches += 1
count = 0
limit = 5
if matches > 1:
print ('Yes! there is a(n)',guess,' in my word.')
guesses += guess
elif matches ==1:
print ('Yes! there is a(n)',guess,' in my word.')
guesses += guess
while count > limit:
input('What do you think my word is')
else:
print('No, there is not a(n)',guess,' in my word.')
guesses += guess
while count > limit:
input('What do you think my word is')
return status
def main():
word = get_word()
guesses = ""
guessed = False
print ('I am thinking of a 3 letter word with no repeating letters. You get five guesses of the letters in my word and then you have to guess the word.')
while not guessed:
text = 'Guess a letter in my word:'
guess = input(text)
guess = guess.upper()
count = 0
limit = 5
if guess in guesses:
print ('You already guessed "' + guess + '"')
elif len(guess) == len(word):
guesses += guess
if guess == word:
guessed = True
else:
print('No, there is not a(n) "' + guess + '"')
elif len(guess) == 1:
guesses += guess
result = check(word,guesses,guess)
if result == word:
guessed = True
else:
print (result)
else:
print ('Invalid entry.')
print ('Yes! you correctly guessed')
main()
For starters while not guessed: will continue until guessed is true -> the word was guessed. Next if you want there to be 5 guesses then an answer guess you want to do for i in range(0, 5): then run your guess logic replacing
if result == word:
guessed = True
with
if result == word:
guessed = true
break
to break out of the loop on a correct guess. Then to allow a guess afterwards, outside of the loop, check if already guessed and allow a guess if not.
Also as a side note you should check that they enter one character with something like
guess = input(text)
while len(guess) != 1:
guess = input(text)
I tried to mostly keep your original code and trail of thought. The main changes I made was getting rid of the check-function as I felt it didn't do anything too useful. I also changed the guessed-variable into a list, and utilized it's properties for your evaluations.
import random
def get_word():
words = ['cat', 'dog', 'man', 'fox', 'jar']
return random.choice(words).upper()
def main():
word = get_word()
guesses = []
guessed = False
print('I am thinking of a 3 letter word with no repeating letters.'
' You get five guesses of the letters in my word and then you have'
' to guess the word.\n')
while not guessed and len(guesses)<5:
text = 'Guess a letter in my word:\n'
guess = input(text)
guess = guess.upper()
if guess in guesses:
print ('You already guessed "', guess, '"\n')
elif len(guess) > 1:
guesses.append(guess)
if guess == word:
guessed = True
else:
print('No, ', guess, 'is not the word!\n')
elif len(guess) == 1:
guesses.append(guess)
if guess in word:
print('Yes there is a(n) ', guess, 'in the word!\n')
else:
print('No, there is not a(n)', guess, 'in the word!\n')
else:
print ('Invalid entry.\n')
if guessed:
print ('You correctly guessed the word!\n')
else:
correct_guesses = [guess for guess in guesses if guess in word]
print('Last chance, what is the full word? (HINT: You have'
'correctly guessed ', str(correct_guesses), ')"')
fword = input()
if fword.upper() == word:
print('You correctly guessed the word!\n')
else: print('Tough luck! You are out of chances! The correct'
'word was ', word, '\n')
main()
playing = True
while playing:
print('Would you like to play again?')
answ = input()
if answ.upper() == 'YES':
main()
else:
print('Thank you for playing.')
playing = False

How to get python to recognize the next occurrence of letter in hangman

My hangman program is fully functioning except there is one problem, let's say the word is mathematics, I guess m, a, t, h, e - but once I guess the other m, it says I guessed it (as opposed to saying "You already guessed this letter") but it doesn't replace the _.
My Code:
def start():
import random
words = ["barbershop", "cuddle", "furious", "demolition", "centaur", "forest", "pineapple", "mathematics", "turkish"]
word = random.choice(words);
hiddenword = len(word) * "-"
used_letters = []
lives = 6
print "Welcome to Hangman! You have 6 guesses, good luck!"
while True:
print word
print "".join(hiddenword)
guess = raw_input("> ")
hiddenword = list(hiddenword)
if len(guess) > 1:
print "Error: 1 Letter Maximum"
elif len(guess) < 1:
guess = raw_input("> ")
else:
if guess.isdigit() == True:
print "Error: Hangman only accepts letters."
else:
if guess in used_letters and word.count(guess) == 1:
print "You already guessed that letter"
else:
if guess.lower() in word:
print "You got the letter " + "'" + guess + "'" + "!"
hiddenword[word.index(guess)] = guess
used_letters.append(guess)
else:
lives -= 1
print "-1 Guesses"
print "Guesses:", lives
used_letters.append(guess)
if lives == 0:
print "GAME OVER: You're out of guesses, try again!"
break
if hiddenword == word:
print "Cangratulations, you got the word!"
break
start()
P.S. - I know I have a lot of excess code e.g. if statements, please do not comment on that.
The problem appears to be with the line:
hiddenword[word.index(guess)] = guess
The string method .index(x) returns the index of the first incidence of x. So this line will persistently fill in the first "m" in mathematics.
Assuming you want the game to reveal all instances of a letter when it is guessed (e.g., show both m's in "mathematics" when you guess "m"), you can substitute this:
for i, x in enumerate(word):
if word[i] == guess:
hiddenword[i] = guess
for your line:
hiddenword[word.index(guess)] = guess
Also, to get the "Congratulations!" message to appear, you will need to change if hiddenword == word to if ''.join(hiddenword) == word, since hiddenword is a list at this point.
Removing multiple occurences of a character in a string in python is easily achieved using:
your_string.replace("m", "");
http://www.tutorialspoint.com/python/string_replace.htm

Python - Dictionary help, checking if a char is in a dictionary object

I have a dictionary object;
secret = {"word" : secretWord}
secretWord being an argument for a string with a single word inside. I also have a string generating an asterisk (*) for every character in the secretWord. In my code I have input from the user which gives a letter.
What I wish to accomplish is to check within the dictionary object secretWord, and if so, replace any asterisk with the input where relevant. However I am not sure how to then save this as a new argument, and then use the next input on the new argument.
Sorry if my question/problem isn't clear, as I am struggling how to word it.
What I want to happen:
for example the secretWord could be 'PRECEDENCE'
>>>
WORD : **********
Guess a letter: e
**E*E*E**E
Guess a letter: p
P*E*E*E**E
etc
What happens:
>>>
WORD : **********
Guess a letter: e
**E*E*E**E
Guess a letter: p
P*********
etc
My current Code:
import random
import sys
def diction(secretWord, lives):
global guess
global secret
secret = {"word" : secretWord, "lives" : lives}
guess = len(secret["word"]) * "*"
print (secret["word"])
print ("WORD: ", guess)
fileName = input("Please insert file name: ")
def wordGuessed(guess, secret):
if guess == secret["word"]:
print ("word is guessed")
if guess != secret["word"]:
print ("word is not guessed")
def livesLeft(inpu):
if inpu not in secret["word"]:
secret["lives"] = secret["lives"] - 1
print("Lives left: ", secret["lives"])
if inpu in secret["word"]:
print("Correct guess")
print(secret["lives"])
def guessCheck(inpu):
for char in secret["word"].lstrip():
if char == inpu:
print (char, end= "")
elif char != secret["word"]:
print ("*", end="")
try:
f = open(fileName)
content = f.readlines()
except IOError as e :
f = None
print("Failed to open", fileName, "- program aborted")
sys.exit()
Run = True
while Run == True:
levelIn = input("Enter difficulty (easy, intermediate or hard): ").lower()
if levelIn == ("easy"):
lives = 10
elif levelIn == ("intermediate"):
lives = 8
elif levelIn == ("hard"):
lives = 5
else:
print("Please input a valid difficulty.")
break
secretWord = (random.choice(content))
secretWord = secretWord.replace("\n", "")
diction(secretWord, lives)
wordGuessed(guess, secret)
while secret["lives"] > 0:
inpu = input("Guess a letter: ").upper()
livesLeft(inpu)
guessCheck(inpu)
if secret["lives"] == 0:
print ("You have no lives left – you have been hung!")
print ("The word was,", secret["word"])
You need to track the guesses made so far, and use those to display the word. Use a set to track what the player already guessed at:
guessed = set()
So that you can do:
if inpu in guessed:
print('You already tried that letter!')
else:
guessed.add(inpu)
whenever a user makes a guess.
You can then use that set to display the word revealed so far:
for char in secret["word"].lstrip():
if char in guessed:
print (char, end="")
else:
print ("*", end="")

Hangman with Arrays in Python 3.2

import random
GameWords = ['COMPUTER', 'PYTHON', 'RUBY', 'DELPHI', 'LAPTOP', 'IDEALS', 'PERL']
#Program will pick a word to use
word = random.randint(0,6)
ChosenWord = GameWords[word]
ChosenWord = list(ChosenWord)
#This will generate a playfield
playField = "_" * len(ChosenWord)
playField = list(playField)
#Array for bad guesses
BadGuess = "_" * len(ChosenWord) * 2
BadGuess = list(BadGuess)
print(" Bad Guesses", BadGuess)
print("\n Hidden Word ", playField, end = "")
#Get the number of letters in the word
WordLength = len(ChosenWord)
#Give two times the number of letters in a word for guessing.
NumChances = WordLength * 2
print("")
print("\n Number of Chances", NumChances)
print("\n This is number of letters in word", WordLength, "\n")
#Need a loop for the guess
flag = True
GoodCounter = 0
b = 0
while flag == True:
#Input a player's guess into two diffrent arrays
#Array for bad guess one for good guess
PlayerGuess = input("\n Guess a letter: ")
PlayerGuess = PlayerGuess.upper()
#Player cannot enter more than one letter
if len(PlayerGuess) != 1:
print("Please enter a single letter.")
#If the player do not enter a letter
elif PlayerGuess not in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
print("Please enter a LETTER.")
#If the player guess wrong
# b is used for indexing
elif PlayerGuess not in ChosenWord:
for b in range(0):
if ChosenWord[b] != PlayerGuess:
BadGuess[b] = PlayerGuess
b = b + 1
print("this is b", b)
print("You have guessed wrong")
print("Letters you have missed", BadGuess)
NumChances = NumChances - 1
print("You have", NumChances, "left!")
if NumChances == 0:
flag = False
print("You have lost!")
else:
flag = True
#If the player guess correctly
# i is used for indexing
elif PlayerGuess in ChosenWord:
for i in range(WordLength):
if ChosenWord[i] == PlayerGuess:
playField[i] = PlayerGuess
print("\n Letters you have HIT! ", playField, end = "")
print("You have guessed correctly")
GoodCounter = GoodCounter + 1
if GoodCounter >= WordLength:
flag = False
print("You have won!")
else:
flag = True
Now I have a new problem my BadGuess array will not display the letters on the play field. I tried to use the same code I used for the playField array but it did not work.
What do I need to do to get the bad guesses to be stored in the BadGuess array and display on the play field?
I don't know if this is what you're asking, but if you want all the bad guesses stored in the array, you have to increment the bad variable.
If you want to replace the blanks, there are many ways to do so, but I'd create a loop that tests to see if a letter is the same as in the word at a given index, and then replace it in the array if it does.
Something like:
for i in range(WordLength):
if ChosenWord[i] == playerGuess:
playField[i] = playerGuess
Hope this helps.

Categories

Resources