Python hangman replacing - python

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.

Related

Infinite loop not checking for string size and belonging to alphabet

I've been trying to make a check for if the input (guesses) belongs to the alphabet and if it's a single character for my simple hangman game, but when I try to run the program it just ignores the entire if sentence. It's been working everywhere else and I just can't find the source of the problem.
Here is my code:
def eng():
letter_list = []
global word
global letter
g = 0
lives = 10
while True:
word = input("Insert The Word: ")
if not word.isalpha():
print("Only letters of the English alphabet are allowed")
else:
print(letter)
break
cls = lambda: print('\n' * 256)
cls()
ready_letters = list(set(word.lower()))
while True:
q = len(ready_letters)
print(q)
while True:
letter = input("Your guess: ")
if not letter.isalpha() and len(letter) != 1:
print("You can make a guess with only one letter of the English alphabet")
else:
break
print(letter_list)
if letter in ready_letters and letter not in letter_list:
letter_list += letter
print("Nice")
g += 1
if g == q:
print(f"The word was: {word}")
print("GG, 🎉🎊")
print("\n")
return
print(f"{g}/{q} letters guessed correctly!")
elif letter in letter_list:
print("You already wrote this letter, try again")
else:
letter_list += letter
print("Oh noie")
lives -= 1
print(f"You have {lives} lives left")
if lives == 0:
print("GG, 웃💀")
return
(read comment)
General tips not related to the issue would also be appreciated.
Thanks for your time!
Simple mistake, instead of using and you should be using or. You want to print our your error message if they type a non-alpha character OR they type more than one letter.

How do I make it so every time I play_again in my hangman game, a new word is generated?

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

How to solve word generation error in Hangman Game?

Q.Building Hangman Game. In the game of Hangman, the player only has 6 incorrect guesses (head, body, 2 legs, and 2 arms) before they lose the game. We loaded a random word list and picked a word from it. Then we wrote the logic for guessing the letter and displaying that information to the user. In this exercise, we have to put it all together and add logic for handling guesses.
So, I made the program with some help but stil there is a silly little problem coming that is the generation of a random word.
Please tell what I am doing wrong and if you would run this program that would help you better understand what I am saying.
import random
def generate():
Words = []
with open('sowpods.txt', 'r') as f:
line = f.readline().strip()
Words.append(line)
while line:
line = f.readline().strip()
Words.append(line)
index = random.randint(0, len(Words) - 1)
return Words[index]
def ask_user_for_next_letters():
letter = input("Guess Your Letter: ")
return letter.strip().upper()
def generate_word_string(word, letter_guessed):
output = []
for letter in word:
if letter in letter_guessed:
output.append(letter.upper())
else:
output.append("_")
return " ".join(output)
print("Welcome To Hangman!")
if __name__ == "__main__":
Secret = generate()
letter_to_guess = set(Secret)
correct_letters = set()
incorrect_letters = set()
num_guesses = 0
while (len(letter_to_guess) > 0) and num_guesses < 6:
guess = ask_user_for_next_letters()
#Checks If We Already Guessed That Letter
if guess in correct_letters or guess in incorrect_letters:
print("You Already Guessed That!")
continue
#If The Guess Was Correct
if guess in letter_to_guess:
#Update The letter_to_guess
letter_to_guess.remove(guess)
#Update The Correct Letters Guessed
correct_letters.add(guess)
else:
incorrect_letters.add(guess)
#Only Update The Number Of Guesses
#If You Guess Incorrectly
num_guesses += 1
word_string = generate_word_string(Secret, correct_letters)
print(word_string)
print("You Have {} Guesses Left".format(6 - num_guesses))
#Tell The User They Have Won Or Lost
if num_guesses < 6:
print("Congratulations! You Correctly Guessed The Word {}!".format(Secret))
else:
print("Loser!".format(Secret))
Modifications
Corrects routine generate to provide random words.
Always convert users input to uppercase
Convert selected word to upper case
slight change in variable naming so it conforms to PEP 8 (i.e. 'secret' rather than 'Secret')
Code
import random
def generate():
words = []
with open('sowpods.txt', 'r') as f:
for line in f:
line = line.strip()
if line:
words.append(line)
return random.choice(words).upper()
def ask_user_for_next_letters():
letter = input("Guess Your Letter: ")
return letter.strip().upper()
def generate_word_string(word, letter_guessed):
output = []
for letter in word:
if letter in letter_guessed:
output.append(letter.upper())
else:
output.append("_")
return " ".join(output)
if __name__ == "__main__":
print("Welcome To Hangman!")
secret = generate()
letter_to_guess = set(secret)
correct_letters = set()
incorrect_letters = set()
num_guesses = 0
while (len(letter_to_guess) > 0) and num_guesses < 6:
guess = ask_user_for_next_letters()
#Checks If We Already Guessed That Letter
if guess in correct_letters or guess in incorrect_letters:
print("You Already Guessed That!")
continue
#If The Guess Was Correct
if guess in letter_to_guess:
#Update The letter_to_guess
letter_to_guess.remove(guess)
#Update The Correct Letters Guessed
correct_letters.add(guess)
else:
incorrect_letters.add(guess)
#Only Update The Number Of Guesses
#If You Guess Incorrectly
num_guesses += 1
word_string = generate_word_string(secret, correct_letters)
print(word_string)
print("You Have {} Guesses Left".format(6 - num_guesses))
#Tell The User They Have Won Or Lost
if num_guesses < 6:
print("Congratulations! You Correctly Guessed The Word {}!".format(secret))
else:
print("Loser!".format(secret))

Python Hangman not ending when player guesses all letters

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)

how to return a string from a for loop instead of printing out one by one

Im trying to make my for loop return a string of the whole word with a dash or each letter depending on guess_letters instead of print out each letter one by one for my hangman game.
Ive tried to print letter as a string, return letter then set a variable to that function then print the variable.
import random
words = ['apple','python','parent']
def randomword(words):
return random.choice(words)
chosenword = randomword(words)
tries = 10
guess_letters = []
def dashshow(guess_letters):
for letter in chosenword:
if letter in guess_letters:
return str(letter)
string_letter = dashshow(guess_letters)
print(string_Letter)
else:
return '-'
dash_letter = dashshow(guess_letters)
print(dash_letter)
def playgame(tries):
while tries != 0 and "_" in chosenword:
print(f"You have {tries} tries left")
guess = str(input("Guess a letter of the word")).lower()
guess_letters.append(guess)
if guess in chosenword:
print("You got a letter correct!")
turns -= 1
else:
print("That letter is not in the word")
turns -= 1
playgame(tries)
I thought it would print out the string with dashes or letters depending on the guessed_letters list but it doesn't print anything.
here is way you can. just modify as you need.Also, You can compare your code with this one. to find mistake.
import random
words = ['apple','python','parent']
def randomword(words):
return random.choice(words)
chosenword = randomword(words)
print (chosenword) #this is random word you can delete this line.
tries = 10
guess_letters = []
def dashshow(guess_letter):
guess_letters.append(guess_letter)
print(guess_letters) # just to debug you can remove.
if len(guess_letters) == len(chosenword):
print("You Won Dear!")
exit()
def playgame(tries):
while tries != 0 :
print(f"You have {tries} tries left")
guess = str(input("Guess a letter of the word:> ")).lower()
if any(guess in s for s in chosenword):
print("You got a letter correct!")
dashshow(guess)
tries -= 1
else:
print("That letter is not in the word")
tries -= 1
playgame(tries)

Categories

Resources