word = input('Enter a word to guess: ')
for n in range(50):
print('')
Lives = 10
playing = True
lettersGuessed = ''
while playing == True:
print(str(Lives)+' Lives left')
if Lives == 0:
playing = False
print('You lose')
else:
for char in word:
if char in lettersGuessed:
print(char, end=' ')
else:
print('_', end=' ')
guess = input('\nEnter a letter to guess: ')
if guess in word:
lettersGuessed += guess
else:
Lives = Lives-1
How would i be able to add a way that the user can win? I've tried comparing the letters guessed with the original word but that didn't work. Any help is greatly appreciated.
The easiest implementation. Add a boolean variable won that is initialized to True; if any _ is printed, set it to False. It remains True only if no _ was printed:
won = True
for char in word:
if char in lettersGuessed:
print(char, end=' ')
else:
print('_', end=' ')
won = False
if won:
print("Hey, you win!")
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
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
I have to write a code in Python where it is about playing the game hangman. Currently my code cannot replace the "_" with the guessed letters properly, where it only replaces one and doesn't show all of the guessed letters.
My code is below:
import random
word = random.choice(["bread", "clouds", "plane"])
guess = 0
correct_guess = 0
play_again = True
print(word)
name = input("Hello, what's your name? ")
print('Hello', name)
status = input('Do you wish to play hangman? Yes/No ')
hyphens = print('_ ' * (len(word)))
if status == 'No' 'no' 'N' 'n':
exit()
while play_again is True:
letter = input('Guess a letter: ')
if letter in word:
guess = guess + 1
correct_guess = correct_guess + 1
print('You guessed a letter correctly!')
position = word.find(letter)
print("The letter is in position", position + 1, "out of", len(word), "in the word. Guess Count:", guess)
if position == 0:
print(letter, "_ _ _ _")
if position == 1:
print("_", letter, "_ _ _ ")
if position == 2:
print("_ _", letter, "_ _ ")
if position == 3:
print("_ _ _", letter, "_ ")
if position == 4:
print("_ _ _ _", letter)
else:
guess = guess + 1
print("That letter isn't in the word. Guess Count:", guess)
if guess == 10:
print('Bad luck. You lost.')
play = input('Do you want to play again? ')
if play == 'No' 'no' 'N' 'n':
exit()
if correct_guess == 5:
print('Congratulations! You have guessed the word! The word was', word + '.')
play = input('Do you want to play again? ')
if play == 'No' 'no' 'N' 'n':
exit()
Your help is very much appreciated. Also, I don't know a lot about programming and I am fairly new to it.
James
you can't write expression like :
if status == 'No' 'no' 'N' 'n':
the correct way is:
if play == 'No' or play == 'no' or play == 'N' or play == 'n':
or:
if play in ['No' ,'no', 'N' ,'n']
one solution:
import random
word = random.choice(["bread", "clouds", "plane"])
print(word)
name = input("Hello, what's your name? ")
print('Hello', name)
status = input('Do you wish to play hangman? Yes/No ')
def play():
if status == 'No' or status == 'no' or status == 'N' or status == 'n':
print ("Goodbye")
return # exit
else:
print('_ ' * (len(word))) # _ _ _ _ _
guess = 0
correct_guess = 0
play_again = True
pos_list = ['_' for x in range(len(word))] # define list where you will put your guessed letters ['_', '_', '_', '_', '_']
while play_again is True:
letter = input('Guess a letter: ')
if letter in word:
guess = guess + 1
correct_guess = correct_guess + 1
print('You guessed a letter correctly!')
position = word.find(letter)
print("The letter is in position", position + 1, "out of", len(word), "in the word. Guess Count:", guess)
pos_list[position] = letter # save letter at position # ['_', '_', '_', 'a', '_']
print (' '.join(pos_list)) # _ _ _ a _
else:
guess = guess + 1
print("That letter isn't in the word. Guess Count:", guess)
if guess == 10:
print('Bad luck. You lost.')
play = input('Do you want to play again? ')
if play == 'No' or play == 'no' or play == 'N' or play == 'n':
print("Goodbye")
return
else:
print('_ ' * (len(word)))
if correct_guess == len(word):
print('Congratulations! You have guessed the word! The word was', word + '.')
play = input('Do you want to play again? ')
if play == 'No' or play == 'no' or play == 'N' or play == 'n':
print("Goodbye")
return
else:
print('_ ' * (len(word)))
play()
Cleaned it up a bit, removing duplicated code. Also that problematic condition:
if status == 'No' 'no' 'N' 'n':
Changed it to:
if status.lower().startswith("n"):
Also important to lower the letter input by the user. Here a full working code.
import random
import re
def start():
status = input('Do you wish to play hangman? Yes/No ')
if status.lower().startswith("n"):
return True
# Computer chooses word
word = random.choice(["bread", "clouds", "plane"])
# Setup game vars
guess = []
game_status = ["_"] * len(word)
while True:
print(" ".join(game_status))
letter = input('Guess a letter: ').lower()
if letter in guess:
print("You already tried that one.")
continue
guess.append(letter)
if letter in word:
print('You guessed a letter correctly!')
positions = [m.start() for m in re.finditer(letter, word)]
for pos in positions:
game_status[pos] = letter
else:
print("That letter isn't in the word.")
if len(guess) == 10:
print(f'Bad luck {name}. You lost. The word was: {word}.')
return
if "_" not in game_status:
print(f'Congratulations {name}! You have guessed the word! The word was {word}.')
return
# Welcome
name = input("Hello, what's your name? ")
print('Hello', name)
while True:
stop = start()
if stop:
break
print("Goodbye!")
print("Welcome to hangman. Are you ready to have some fun?")
def play():
import random
List = ["random", "words", "list"]
word = str(random.choice(List))
mistake = 7
alreadySaid = set()
board = "_" * len(word)
print(" ".join(board))
while mistake > 0:
while True:
guess = input("Please guess a letter: ")
if len(guess) <= 1:
break
else:
print("Too long. Enter only one letter.")
if guess in word:
alreadySaid.add(guess)
print("Correct!",guess, " was in the word!")
board = "".join([guess if guess in word else "_" for str in word])
if board == word:
print("Congratulations! You´re correct!!!")
elif guess not in word:
mistake -= 1
print("Wrong!", mistake," mistakes remaining.")
if mistake <= 0:
print("Game Over")
print(" ".join(board))
play()
I'm trying to make hangman with python 3 but whenever I input a correct letter it comes out as a word of only that letter. For example for random when I input r the output is r r r r r r when I want r _ _ _ _ _. What do you think is wrong? Also do I have any other problems?
Might I suggest you take a step back and try a different, cleaner approach? Besides that, I suggest you keep your hidden word as a list, since strings are immutable and do not support item assignment, which means you cannot reveal the character if the user's guess was correct (you can then join() it when you need it to display it to the user as a string):
import random
word_list = [
'spam',
'eggs',
'foo',
'bar'
]
word = random.choice(word_list)
guess = ['_'] * len(word)
chances = 7
while '_' in guess and chances > 0:
print(' '.join(guess))
char = input('Enter char: ')
if len(char) > 1:
print('Please enter only one char.')
continue
if char not in word:
chances -= 1
if chances == 0:
print('Game over!')
break
else:
print('You have', chances, 'chances left.')
else:
for i, x in enumerate(word):
if x == char:
guess[i] = char
else:
print(''.join(guess))
print('Congratulations!')
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")