Hangman reading input file from user - python

What I am trying to do is to read a text file from a user and then run the game with that particular file. I know that it will be more easier to have functions but I don't know how to modify the whole code with functions.
How can I run the game with that text file inputted by user?
import random
import sys
choice = None
while choice != "0":
print('''
--------------------
Welcome to Hangman
--------------------
Please select a menu option:
0 - Exit
1 - Enter a new text file to be read:
2 - Play Game
''')
choice= input("Enter you choice: ")
if choice == "0":
sys.exit("Exiting from Python")
elif choice =="1":
newIn = []
fileInput = input("Enter a new text file name: ")
newIn = open(fileInput).readlines()
newIn=List
elif choice == "2":
List = open("words_for_hangman.txt").readlines()
print('''
Now select your difficulty level:
0 - EASY
1 - INTERMEDIATE
2 - HARD
''')
level= input("Enter your choice: ")
if level == "0":
word = random.choice(List)
word = word.strip()
hidden_word = "*" * len(word)
lives = 10
guessed = []
elif level == "1":
word = random.choice(List)
word = word.strip()
hidden_word = "*" * len(word)
lives = 7
guessed = []
elif level == "2":
word = random.choice(List)
word = word.strip()
hidden_word = "*" * len(word)
lives = 5
guessed = []
while lives != 0 and hidden_word != word:
print("\n-------------------------------")
print("The word is")
print(hidden_word.replace("_"," _ "))
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()
elif guess== " ":
guess = input("\n You need to input a letter, not a space!\n Come on let's 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 have 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 = print("\n That is not a valid option! Please try again!")
choice = input("Choice: ")

At first sight, there are two mistakes in the program
The lines
newIn = open(fileInput).readlines()
newIn=List
first read the file into the variable newIn and then remove the content of newIn by setting it to the content of List. I guess you wanted to do
List = open(fileInput).readlines()
as you did in the second part.
The second mistake is that the whole game is played only when the user presses 2. Try moving the whole block beginning with
while lives != 0 and hidden_word != word:
to the left, so that block is entered either when the user presses 1 or 2. Also, if you do this, the else at the end of the program should go right before the while lives != 0...

First keep all your files in a folder and run this file..
For choice 1: Give your new.txt file or try with same file of option two.(words_for_hangman.txt) but it will be easy for your if you keep all your files in same folder.
import random
import sys
choice = None
while choice != "0":
print('''
--------------------
Welcome to Hangman
--------------------
Please select a menu option:
0 - Exit
1 - Enter a new text file to be read:
2 - Play Game
''')
choice= input("Enter you choice: ")
if choice == "0":
sys.exit("Exiting from Python")
elif choice =="1":
newIn = []
fileInput = input("Enter a new text file name: ")
newIn = open(fileInput).readlines()
newIn=List
elif choice == "2":
List = open("words_for_hangman.txt").readlines()
print('''
Now select your difficulty level:
0 - EASY
1 - INTERMEDIATE
2 - HARD
''')
level= input("Enter your choice: ")
if level == "0":
word = random.choice(List)
word = word.strip()
hidden_word = "*" * len(word)
lives = 10
guessed = []
elif level == "1":
word = random.choice(List)
word = word.strip()
hidden_word = "*" * len(word)
lives = 7
guessed = []
elif level == "2":
word = random.choice(List)
word = word.strip()
hidden_word = "*" * len(word)
lives = 5
guessed = []
while lives != 0 and hidden_word != word:
print("\n-------------------------------")
print("The word is")
print(hidden_word.replace("_"," _ "))
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()
elif guess== " ":
guess = input("\n You need to input a letter, not a space!\n Come on let's 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 have 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 = print("\n That is not a valid option! Please try again!")
choice = input("Choice: ")

Related

Guess the word - Python (more guesses than should be)

I am trying to make a game where the user inputs a word with only three guesses available, but instead it keeps allowing four guesses which I don't want.
When i input a word and my guess_count reaches 3, i am supposed to be sent this msg "You have no more guesses, you lose!" then ask if i want to retry but instead it lets me play one more time thereby exceeding the guess_limit
Here is my code
secret_word = "loading"
guess_word = ""
guess_count = 0
guess_limit = 3
end = False
print("Welcome to the guessing game\nYou have 3 guesses")
guess_word = input("Enter a word: ")
def end_msg(msg):
print(msg)
retry = input("Do you want to play again? ")
if (retry == "yes") :
global end, guess_word, guess_count
end = False
guess_word = ""
guess_count = 0
print("Welcome to the guessing game\\nYou have 3 guesses")
guess_word = input("Enter a word: ")
else:
end = True
while (not(end)) :
if (guess_word != secret_word and guess_count \< guess_limit):
guess_count += 1
print("Incorrect!")
print("You have " + str(3 - guess_count) + " left!")
guess_word = input("Try again: ")
elif (guess_count == 3):
end_msg("You have no more guesses, you lose!")
else:
end_msg("Correct, you win")
I see your query already answered above, In case you want I have adapted your code to make it more organized and structured into two functions
playagain - which asks after winning/losing if the user wants to play the game again
play - the actual program to play the game
I removed some redundancies like end = False variable you used and could have also removed some other variables like guess_limiter (by just assigning the guess limit value in the actual program) but I wanted to retain your code as much as possible in case for your understanding, hope this helps
def playagain():
play_again = input("Do you want to play again? (y/n) ")
if play_again == 'y':
return play()
elif play_again == 'n':
print("Thank you for playing")
else:
print("incorrect input please try again")
playagain()
def play():
secret_word = "loading"
guess_word = ""
guess_count = 1
guess_limit = 3
print("Welcome to the guessing game\nYou have 3 guesses")
while (guess_count != guess_limit + 1):
guess_word = input("Enter a word: ")
if guess_word == secret_word:
print("Correct, you win")
playagain()
break
elif guess_count == guess_limit:
print("You have no more guesses, you lose!")
playagain()
break
else:
print("Incorrect!")
print("You have " + str(3 - guess_count) + " left!")
guess_count += 1
play()
You are getting this bug because you wrote guess_limit = 3. You know Programs count from 0, so you need to enter 1 less from your desire try. It should be guess_limit = 2.
And also you wrote elif (guess_count == 3) :, thats mean if guess_count == 3 your will get "You have no more guesses, you lose!" even, user put the right answer. so it should be
elif (guess_word != secret_word and guess_count == 2):
so your final code should be:
secret_word = "loading"
guess_word = ""
guess_count = 0
guess_limit = 2
end = False
print("Welcome to the guessing game\nYou have 3 guesses")
guess_word = input("Enter a word: ")
def end_msg (msg) :
print(msg)
retry = input("Do you want to play again? ")
if (retry == "yes") :
global end, guess_word, guess_count
end = False
guess_word = ""
guess_count = 0
print("Welcome to the guessing game\\nYou have 3 guesses")
guess_word = input("Enter a word: ")
else:
end = True
while (not(end)) :
if (guess_word != secret_word and guess_count < guess_limit) :
guess_count += 1
print("Incorrect!")
print("You have " + str(3 - guess_count) + " left!")
guess_word = input("Try again: ")
elif (guess_word != secret_word and guess_count == 2) :
end_msg("You have no more guesses, you lose!")
else:
end_msg("Correct, you win")

Creating a guessing game in Python using while and for loops

I am trying to make a guess game. I've used while, if, elif, and else statements but I'm stuck on how to use for and while loops as well as randomizing single hints and single answers from a nested lists.
black_box = ["guam","lakers","flash","buddha","drake","fortnite","annabelle","xmen","mars","dad"]
nested_list = [["island","yigo","cocos","kelaguen"],["kobe","la","magic","lebron"],["scarlet","speedster","dc","ezra"], ["asiangod","meditation","monk","enlightenment"],["rapper","onedance","canadian","raptors"],["game","epic","notminecraft","dances"],["doll","conjuring","soultaker","creation"],["wolverine","mystique","magneto","apocalypse"],["red","fourth","planet","ares"], ["man","american","peter","lionking"]]
i = random.randint(0,9)
word = black_box[i]
hint = nested_list[i]
print("Guess the word with the following hint: ", hint, "you have 4 tries.")
numofguesses = 0
guess = input("What is the word? ")
while numofguesses < 4:
numofguesses = numofguesses + 1
if guess == word:
print("You win!")
option = input("Do you want to try again or quit? ")
if option == "try again":
print("")
elif option == "quit":
break
if guess != word:
print("Try again!")
guess = input("What is the word? ")
if guess != word:
print("Try again!")
guess = input("What is the word? ")
I expected to get a line of code that prints "Try again!" but it skipped and started to print "What is the word? " print("Guess the word with the following hint: ", hint, "you have 4 tries.") Originally, I used hint[i] which printed out only one hint in the nested list but then I tried to run the program again but I got an error saying, "list index is out of range.
Your condition checks and loops where not correct. Try the below code, it should work fine.
black_box = ["guam","lakers","flash","buddha","drake","fortnite","annabelle","xmen","mars","dad"]
nested_list = [["island","yigo","cocos","kelaguen"],["kobe","la","magic","lebron"],["scarlet","speedster","dc","ezra"], ["asiangod","meditation","monk","enlightenment"],["rapper","onedance","canadian","raptors"],["game","epic","notminecraft","dances"],["doll","conjuring","soultaker","creation"],["wolverine","mystique","magneto","apocalypse"],["red","fourth","planet","ares"], ["man","american","peter","lionking"]]
while True:
i = random.randint(0, 9)
word = black_box[i]
numofguesses = 0
while numofguesses < 4:
hint = nested_list[i][numofguesses]
print("Guess the word with the following hint: ", hint, ". You have ", 4 - numofguesses, " tries!")
guess = input("What is the word? ")
numofguesses = numofguesses + 1
if guess == word:
print("You win!")
break
if guess != word:
print("Try again!")
option = input("Do you want to try again or quit? ")
if option == "try again":
print("")
else:
break

Converting a list of ints into something compatible with locations in another list While creating a Hangman game

I've been working on hangman project recently, I have used enumerate to get the locations of a letter that's been guessed so i can put it into a list, but when i try and put it into "guess" list, it comes up with:
Edit: I do understand that you cannot simply change an entire list into a series of ints by doing int(list), it's simply a place holder
Here is my code
import random
lines = []
with open('words.txt', 'r') as f:
for line in f:
line = line.strip()
lines.append(line)
choice = random.choice(lines)
#print("it says", choice)
guessed = False
print("Your word is", len(choice), "letters long!")
answer = ["_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_"]
wrong = 0
= 1
print(choice)
while not guessed:
guess = input("Guess a letter!")
#location = choice.find(guess)
location = [i for i, a in enumerate(choice) if a == guess]
print(location)
if wrong == 6:
print("Sorry, you have killed yourself.")
guessed = True
elif not location:
wrong += 1
print("Sorry, that was not part of the word!")
print("You have", (6 - wrong), "guesses left")
elif right == len(choice):
answer[int(location)] = guess
print(answer[0:len(choice)])
print("Congratulations! You have won!")
guessed = True
else:
right += 1
answer[location] = guess
print(answer[0:len(choice)])
Your code has other issues beyond this but as your question at hand, it is here:
elif right == len(choice):
answer[int(location)] = guess
print(answer[0:len(choice)])
print("Congratulations! You have won!")
guessed = True
else:
right += 1
answer[location] = guess
print(answer[0:len(choice)])
Your two statements answer[int(location)] = guess and answer[location] = guess if you print location it is a list, for a 4 letter word example vash, location is a list of range [0,3] you are attempting to pass the entire list as an index which will not work regardless if you convert it to int or not.
Please try this modification, this is not a full solution, I do not want to take away from your journey on this project but this will get your moving:
import random
lines = ['hey', 'this', 'that']
choice = random.choice(lines)
#print("it says", choice)
guessed = False
print("Your word is", len(choice), "letters long!")
answer = ["_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_"]
wrong = 0
right = 0
print(choice)
while not guessed:
guess = input("Guess a letter!")
#location = choice.find(guess)
if wrong == 6:
print("Sorry, you have killed yourself.")
guessed = True
elif guess not in choice:
wrong += 1
print("Sorry, that was not part of the word!")
print("You have", (6 - wrong), "guesses left")
elif right == len(choice):
print(answer)
print("Congratulations! You have won!")
guessed = True
else:
right += 1
answer[choice.index(guess)] = guess
print(answer[0:len(choice)])

Hangman drawing regardless of correct letters (Python, turtle)

I'm creating a hangman game in Python 3.5.1 and everything is going well except for when it comes to the guessing part. I print "Hurray" when the letter is guessed correctly and I have it draw an additional body part when it is not guessed correctly. My problem is that even when a letter is guessed correctly it will also draw another body part:
import drawHangman
import turtle
import random
def main():
window = turtle.Screen()
window.setup(400, 400, 200, 200)
HG = turtle.Turtle()
drawHangman.default(HG)
wrongGuess = 0
maxGuesses = 0
lines = open('wordlist.txt').read().splitlines()
myline =random.choice(lines)
print(myline)
name = input("Welcome to hangman! What is your name? \n")
print("Welcome", name + "! \n The rules are as follows: \n 1) No looking at answer list! \n 2) Do not have fun!! \n 3) No hacking my game!")
tos = input("Do you accept the rules provided above? Type Yes or No. \n")
if tos == "no":
print("Who cares! The rules suck anyways!")
elif tos == "yes":
print("HI")
else:
print("You don't listen very well. I guess proceed ugh")
while maxGuesses < 6:
guess = input("Please input your guess!")
maxGuesses += 1
for char in myline:
if char in guess:
print("Hurray")
else:
wrongGuess += 1
print("You have", 6 - maxGuesses, "guesses left!")
if wrongGuess == 1:
drawHangman.drawHead(HG)
elif wrongGuess == 2:
drawHangman.drawBody(HG)
elif wrongGuess == 3:
drawHangman.drawLeftArm(HG)
elif wrongGuess == 4:
drawHangman.drawRightArm(HG)
elif wrongGuess == 5:
drawHangman.drawLeftLeg(HG)
elif wrongGuess == 6:
drawHangman.drawRightLeg(HG)
else:
playAgain = input('Do you want to play again? (yes or no)')
if playAgain == "yes":
drawHangman.reset(HG)
main()
else:
print("Thanks for playing!")
return
main()
I know it has something to do with the part where else tells it there is a wrong letter but I can't figure it out. I've tried indenting it one more space, but that just prints the amount of guesses left. Any help is appreciated.
PS. The drawHangman.* routines come from a file I have in my src folder that contains body parts.
You have indented the else clause (and the following lines) incorrectly - it's in the scope of the for loop instead of the if statement:
for char in myline:
if char in guess:
print("Hurray")
else:
wrongGuess += 1
print("You have", 6 - maxGuesses, "guesses left!")
if wrongGuess == 1:
drawHangman.drawHead(HG)
# etc.
As you wrote it, the else clause and all the drawings are executed only after the entire for loop has finished.
Besides the problem raised in your question, there seem to be other issues with your code: your logic assumes/hardcodes 6 letter words; you're repeat game logic is actually recursive; you don't close the words file after you're finished with it; your yes/no question handling isn't robust; you repeat things, by recalling main(), that need only be done once; you don't display the current correct/unknown letter status.
Below is a rework of your code to address these issues and play an actual game of hangman:
from turtle import Turtle, Screen
import random
import drawHangman
BODY_PARTS = [ \
drawHangman.drawHead, drawHangman.drawBody, drawHangman.drawLeftArm, \
drawHangman.drawRightArm, drawHangman.drawLeftLeg, drawHangman.drawRightLeg, \
]
MAXIMUM_WRONG_GUESSES = len(BODY_PARTS)
def hangman(HG):
drawHangman.default(HG)
with open('wordlist.txt') as file:
lines = file.read().splitlines()
word = random.choice(lines)
letters = set(word)
wrongGuesses = 0
while letters and wrongGuesses < MAXIMUM_WRONG_GUESSES:
for letter in word:
print("*" if letter in letters else letter, end="")
print(".")
letter = input("Please input your guess: ")
if letter in letters:
print("Hurray!")
letters.remove(letter)
else:
BODY_PARTS[wrongGuesses](HG)
wrongGuesses += 1
print("You have", MAXIMUM_WRONG_GUESSES - wrongGuesses, "guesses left!")
def main():
screen = Screen()
screen.setup(400, 400, 200, 200)
turtle = Turtle()
playAgain = True
print("Welcome to hangman!")
name = input("Enter your name: ")
print("Welcome", name + "!")
print("The rules are as follows:")
print(" 1) No looking at answer list!")
print(" 2) Do not have fun!!")
print(" 3) No hacking my game!")
tos = input("Do you accept the rules provided above? (yes or no): ")
if tos.lower().startswith("n"):
print("Who cares! The rules suck anyways!")
elif tos.lower().startswith("y"):
print("Hi")
else:
print("You don't listen very well. I guess proceed ugh")
while playAgain:
hangman(turtle)
answer = input('Do you want to play again? (yes or no): ')
playAgain = answer.lower().startswith("y")
if playAgain:
drawHangman.reset(turtle)
else:
print("Thanks for playing!")
main()

HANGMAN assignment python

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")

Categories

Resources