My problem is that when I run the program and get all the letters correct, it does not move on from there and I'm in an infinite loop. I expect it to say "Good Job!" and end the program when the player gets the word right. I am very new to coding, and would greatly appreciate any help.
import random
import time
name = input("What is your name? ")
print(name + ", ay?")
time.sleep(1)
start = input("Up for a game of Hangman?(y/n) ")
lis = random.choice(["yet"])
dash = []
while len(dash) != len(lis):
dash.append("_")
guess = []
guesscomb = "".join(guess)
wrongcount=int(0)
alphabet = "abcdefghijklmnopqrstuvwxyz"
if start == "y":
print("One game of Hangman comin' right up,",name)
letter = input("Alright then, Guess a letter: ")
thing = ''.join(dash)
while guesscomb != thing:
if letter == "" or letter == " " or len(letter) != 1:
print("I don't understand. Please only use singular letters.")
letter = input("Guess a letter: ")
elif letter in lis and letter in alphabet:
print("Nice!")
location = lis.find(letter)
dash[location] = letter
guess.append(letter)
alphabet.replace(letter," ")
guesscomb = "".join(guess)
letter = input("Guess a letter: ")
else:
print("Wrong.")
wrongcount = wrongcount + 1
print("Total Mistakes:",wrongcount)
letter = input("Guess a letter: ")
elif start == "n":
input("Shame.")
quit()
print("Good Job!")
time.sleep(10)
The thing variable is equal to ___ while lis is always equal to "yet".
guesscomb cannot be equal to thing as you validate a letter when the guess is equal to a letter in lis
You can use print with the parameter end="" so that the cursor don't go new line.
You can use the method isalpha on string to check if it is all characters instead of comparing it with the alphabets.
And as Ben said, thing is always ___
Modify this part of your code, and it will work
if start == "y":
print("One game of Hangman comin' right up,", name)
print("Alright then, ", end="")
# letter = input("Alright then, Guess a letter: ")
thing = ''.join(dash)
while guesscomb != thing:
letter = input("Guess a letter: ")
if letter == "" or letter == " " or len(letter) != 1:
print("I don't understand. Please only use singular letters.")
elif letter in lis and letter in alphabet:
print("Nice!")
location = lis.find(letter)
dash[location] = letter
guess.append(letter)
alphabet.replace(letter, " ")
guesscomb = "".join(guess)
else:
print("Wrong.")
wrongcount = wrongcount + 1
print("Total Mistakes:", wrongcount)
thing = ''.join(dash)
Related
Basically the title. I want my hangman game to generate a new random word from an imported file list every time I play again. However, when I do it it simply utilizes the same word as before. Here is the code.
import random
with open("English_Words", "r") as file:
allText = file.read()
words = list(map(str, allText.split()))
word = random.choice(words)}
def play_again():
print("Do you want to play again (Yes or No)")
response = input(">").upper()
if response.startswith("Y"):
return True
else:
return False
def singleplayer():
guessed = False
word_completion = "_" * len(word)
tries = 6
guessed_letters = []
while not guessed and tries > 0:
print(word_completion)
print(hangman_error(tries))
print(guessed_letters)
guess = input("Guess a letter:").lower()
if guess in guessed_letters:
print("You have already guessed that letter.")
elif guess not in word:
print("[INCORRECT] That letter is not in the word!")
guessed_letters.append(guess)
tries -= 1
if tries == 0:
print("You ran out of tries and hanged the man! The word or phrase was: " + str(word))
elif guess in word:
print("[CORRECT] That letter is in the word!")
guessed_letters.append(guess)
word_as_list = list(word_completion)
indices = [i for i, letter in enumerate(word) if letter == guess]
for index in indices:
word_as_list[index] = guess
word_completion = "".join(word_as_list)
if "_" not in word_completion:
guessed = True
if tries == 0:
print("You ran out of tries and hanged the man! The word or phrase was: " + str(word))
if "_" not in word_completion:
guessed = True
if guessed:
print("You win, the man was saved! The word was:" + str(word))
while True:
singleplayer()
if play_again():
continue
else:
break
You need to call word = random.choice(words) inside of your singleplayer() function. Preferrably at the top, either right above or right below the guess = False line.
This way, you're program is going to call that random choice line everytime you call the singleplayer function.
def singleplayer():
word = random.choice(words)
guessed = False
I am posting for the first time on Stackoverflow and I don't know if I am doing this the right way, but I am looking to store all letters that the user guessed in a list and if the list is equal to the word, the user wins.
thanks :)
CODE :
word = "apache"
word_list = [x for x in word]
print("The word is ", "_ " * len(word))
final = []
while True:
guess = input("Your guess : ").lower().strip()
if guess.isalpha() and len(guess) == 1 or len(guess) == len(word):
if guess == word or final == word_list:
print("Good joby you have guessed the word!")
break
elif guess in word:
final = "".join(x if x in guess else "_ " for x in word_list)
print("".join(final))
elif len(guess) == len(word) and guess != word:
print("Sorry mate, wrong word")
elif guess not in word:
print("Wrong guess")
else:
print("\nYou need to either enter a word of the same length or a letter\n")
This is the bug I get :
Your guess : a,
a_ a_ _ _
Your guess : p,
_ p_ _ _ _
Your guess : c,
_ _ _ c_ _
Your guess :
It won't store all the letters I guessed before but only the letter I just recently guessed
The first problem is as #Paritosh Singh said you overwrite final. You are also declaring final as a list and overwrite it with a string (which is legal in python). final is probably a string and you need to update it not overwrite it :
word = "apache"
word_list = [x for x in word]
print("The word is ", "_ " * len(word))
final = ""
while True:
guess = input("Your guess : ").lower().strip()
if guess.isalpha() and len(guess) == 1 or len(guess) == len(word):
if guess == word or final == word_list:
print("Good joby you have guessed the word!")
break
elif guess in word:
final = "".join(x if x in guess or x in final else "_ " for x in word_list)
if final == word:
print("Good joby you have guessed the word!")
break
else:
print(final)
elif len(guess) == len(word) and guess != word:
print("Sorry mate, wrong word")
elif guess not in word:
print("Wrong guess")
else:
print("\nYou need to either enter a word of the same length or a letter\n")
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
For an assignment I need to write a basic HANGMAN game. It all works except this part of it...
The game is supposed to print one of these an underscore ("_") for every letter that there is in the mystery word; and then as the user guesses (correct) letters, they will be put in.
E.G
Assuming the word was "word"
User guesses "W"
W _ _ _
User guesses "D"
W _ _ D
However, in many cases some underscores will go missing once the user has made a few guesses so it will end up looking like:
W _ D
instead of:
W _ _ D
I can't work out which part of my code is making this happen. Any help would be appreciated! Cheers!
Here is my code:
import random
choice = None
list = ["HANGMAN", "ASSIGNEMENT", "PYTHON", "SCHOOL", "PROGRAMMING", "CODING", "CHALLENGE"]
while choice != "0":
print('''
******************
Welcome to Hangman
******************
Please select a menu option:
0 - Exit
1 - Enter a new list of words
2 - Play Game
''')
choice= input("Enter you choice: ")
if choice == "0":
print("Exiting the program...")
elif choice =="1":
list = []
x = 0
while x != 5:
word = str(input("Enter a new word to put in the list: "))
list.append(word)
word = word.upper()
x += 1
elif choice == "2":
word = random.choice(list)
word = word.upper()
hidden_word = " _ " * len(word)
lives = 6
guessed = []
while lives != 0 and hidden_word != word:
print("\n******************************")
print("The word is")
print(hidden_word)
print("\nThere are", len(word), "letters in this word")
print("So far the letters you have guessed are: ")
print(' '.join(guessed))
print("\n You have", lives,"lives remaining")
guess = input("\n Guess a letter: \n")
guess = guess.upper()
if len(guess) > 1:
guess = input("\n You can only guess one letter at a time!\n Try again: ")
guess = guess.upper()
while guess in guessed:
print("\n You have already guessed that letter!")
guess = input("\n Please take another guess: ")
guess = guess.upper()
guessed.append(guess)
if guess in word:
print("*******************************")
print("Well done!", guess.upper(),"is in the word")
word_so_far = ""
for i in range (len(word)):
if guess == str(word[i]):
word_so_far += guess
else:
word_so_far += hidden_word[i]
hidden_word = word_so_far
else:
print("************************")
print("Sorry, but", guess, "is not in the word")
lives -= 1
if lives == 0:
print("GAME OVER! You ahve no lives left")
else:
print("\n CONGRATULATIONS! You have guessed the word")
print("The word was", word)
print("\nThank you for playing Hangman")
else:
choice = input("\n That is not a valid option! Please try again!\n Choice: ")
You have hidden_word = " _ " * len(word)
This means that at start for a two letter word, you have [space][underscore][space][space][underscore][space].
When you then do word_so_far += hidden_word[i], for i = 0, you will append a space, not an underscore.
The quickest fix would seem to be:
Set hidden_word to just be _'s (hidden_word = " _ " * len(word))
When you print out the word, do
hidden_word.replace("_"," _ ") to add the spaces around the underscores back
#Foon has showed you the problem with your solution.
If you can divide your code up into small functional blocks, it makes it easier to concentrate on that one task and it makes it easier to test. When you are having a problem with a specific task it helps to isolate the problem by making it into a function.
Something like this.
word = '12345'
guesses = ['1', '5', '9', '0']
def hidden_word(word, guesses):
hidden = ''
for character in word:
hidden += character if character in guesses else ' _ '
return hidden
print(hidden_word(word, guesses))
guesses.append('3')
print(hidden_word(word, guesses))
Below code solves the problem.you can do some modifications based on your requirement.If the Guessed letter exists in the word.Then the letter will be added to the display variable.If not you can give a warning .But note that it might tempt you to write ELSE statement inside the for loop(condition:if guess not in word).If you do like that then the object inside the Else statement will be repeated untill the For loop stops.so that's why it's better to use a separete IF statement outside the for loop.
word="banana"
display=[]
for i in word:
display+="_"
print(display)
while True:
Guess=input("Enter the letter:")
for position in range(len(word)):
if Guess==word[position]:
display[position]=word[position]
print(display)
if Guess not in word:
print("letter Doesn't exist")
So I'm writing a hangman program and I'm having trouble getting the current guesses to display as underscores with the correct letters guessed replacing an underscore. I can get the function to work once (thats the insert_letter function) and I know its just replacing every time it goes through the loop, but I can't return the new current without quitting the loop so if someone could offer another way to get the guesses to keep updating that would be great!
def insert_letter(letter, current, word):
current = "_" * len(word)
for i in range (len(word)):
if letter in word[i]:
current = current[:i] + letter + current[i+1:]
return current
def play_hangman(filename, incorrect):
words = read_words(filename)
secret_word = random.choice(words)
num_guess = 0
letters_guessed = set()
letter = input("Please enter a letter: ")
while num_guess < incorrect:
letter = input()
if letter in secret_word:
current = insert_letter(letter, current, secret_word)
print(current)
else:
num_guess += 1
current = "_" * len(secret_word)
print(current)
letters_guessed.add(letter)
You didn't show the code for your insert_letter() function so I wrote an alternative -- display_remaining(). Give this a try:
import random, sys
def play_hangman(filename, incorrect):
words = read_words(filename)
secret_word = random.choice(words)
num_guess = 0
letters_guessed = set()
while num_guess < incorrect:
letter = input("Please enter a letter: ")
letters_guessed.add(letter)
current = display_remaining(secret_word, letters_guessed)
print(current)
if not letter in secret_word:
print("Incorrect guess.")
num_guess += 1
if not '_' in current:
print("Congratulations! You've won!")
sys.exit(0)
print("Sorry. You've run out of guesses. Game over.")
def display_remaining(word, guessed):
replaced = word[:]
for letter in word:
if (not letter == '_') and letter not in guessed:
replaced = replaced.replace(letter, '_', 1)
return replaced
def read_words(filename):
with open(filename, 'rU') as f:
return [line.strip() for line in f]
if __name__ == '__main__':
play_hangman('words.txt', 6)
NOTE: With this implementation, your words file shouldn't have any words containing the underscore character.