Python Hangman game and replacing multiple occurrences of letters - python

This is my first year programming with Python.
I am trying to create a hangman game.
So my questions: how do I check for
If the person is guessing a letter that has already been guessed and where to include it.
Check they are inputting a valid letter not multiple letters or a number.
What happens if it's a word such as 'Good' and they guess an 'o' at the moment my code breaks if this is the case. Also where on Earth would this be included in the code?
Here is my code
import random
import math
import time
import sys
def hangman():
if guess == 5:
print " ----------|\n /\n|\n|\n|\n|\n|\n|\n______________"
print
print "Strike one, the tigers are getting lonely!"
time.sleep(.5)
print "You have guessed the letters- ", guessedLetters
print " ".join(blanks)
print
elif guess == 4:
print " ----------|\n / O\n|\n|\n|\n|\n|\n|\n______________"
print
print "Strike two, pressure getting to you?"
time.sleep(.5)
print "You have guessed the letters- ", guessedLetters
print " ".join(blanks)
print
elif guess == 3:
print " ----------|\n / O\n| \_|_/ \n|\n|\n|\n|\n|\n______________"
print
print "Strike three, are you even trying?"
time.sleep(.5)
print "You have guessed the letters- ", guessedLetters
print " ".join(blanks)
print
elif guess == 2:
print " ----------|\n / O\n| \_|_/ \n| |\n|\n|\n|\n|\n______________"
print
print "Strike four, might aswell giveup, your already half way to your doom. Oh wait, you can't give up."
time.sleep(.5)
print "You have guessed the letters- ", guessedLetters
print " ".join(blanks)
print
elif guess == 1:
print " ----------|\n / O\n| \_|_/ \n| |\n| / \\ \n|\n|\n|\n______________"
print
print "One more shot and your done for, though I knew this would happen from the start"
time.sleep(.5)
print "You have guessed the letters- ", guessedLetters
print " ".join(blanks)
print
elif guess == 0:
print " ----------|\n / O\n| \_|_/ \n| |\n| / \\ \n| GAME OVER!\n|\n|\n______________"
print "haha, its funny cause you lost."
print "p.s the word was", choice
print
words = ["BAD","RUGBY","JUXTAPOSED","TOUGH","HYDROPNEUMATICS"]
choice = random.choice(words)
lenWord = len(choice)
guess = 6
guessedLetters = []
blanks = []
loading = ".........."
print "Loading",
for char in loading:
time.sleep(.5)
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(.5)
print "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
print "Great I'm glad to see you have finally woken."
time.sleep(1)
raw_input("Did you have a nice journey? ")
time.sleep(2)
print """
Oh wait, I don't care.
I have brought you to this island simply for my amusment. I also get paid to do this.
"""
time.sleep(2)
print"""
Don't worry this isn't all for nothing.
I'm sure the tigers will enjoy your company.
"""
time.sleep(2)
print"""
Hold on, let us make things interesting.
"""
time.sleep(2)
print "I will let you live if you complete an impossible game!"
time.sleep(2)
print "A game know as hangman!"
time.sleep(2)
print "HAHAHAHAHAH, I am so evil, you will never escape!"
time.sleep(2)
print "Enjoy your stay :)"
time.sleep(1)
print
print "Alright lets begin! If you wish to guess the word type an '!' and you will be prompted"
time.sleep(.5)
print
for s in choice:
missing = choice.replace(choice, "_")
blanks.append("_")
print missing,
print
time.sleep(.5)
while guess > 0:
letterGuess = raw_input("Please enter a letter: ")
letterGuess = letterGuess.upper()
if letterGuess == "!":
print "If you guess the FULL word correcly then you win, if incorrect you die. Simple."
fullWordGuess = raw_input("What is the FULL Word? ")
fullWordGuess = fullWordGuess.upper()
if fullWordGuess == choice:
print "You must have hacked this game"
time.sleep(.5)
print "Looks like you beat an impossible game! \nGood Job \nI'll show myself out."
break
else:
print "You lost, I won, you're dead :) Have a nice day!"
print "P.S The word was ", choice
break
else:
print
if letterGuess in choice:
location = choice.find(letterGuess)
blanks.insert(location, letterGuess)
del blanks[location+1]
print " ".join(blanks)
guessedLetters.append(letterGuess)
print
print "You have guessed the letters- ", guessedLetters
if "_" not in blanks:
print "Looks like you beat an impossible game! \nGood Job \nI'll show myself out."
break
else:
continue
else:
guessedLetters.append(letterGuess)
guess -= 1
hangman()

I did not really follow your code since there seems to be something wrong with your indentation, and the many print's confused me a little, but here is how I would suggest soving your Questions:
1.1. Create a list of guessed characters:
guessed_chars = []
if(guess in guessed_chars):
guessed_chars.append(guess)
#do whatever you want to do with the guess.
else:
print("You already guessed that.")
#do what ever you want to do if you already guessed that.
1.2 Lets say the word the player has to ges is word = "snake". To get the indices (since a string is just a list of charcters in python, only that it is immutable) where the guessed letter is in the word you could then use something like:
reveal = "_"*len(word)
temp = ""
for i, j in enumerate(word):
if j == guess:
temp += guess
else:
temp += reveal[i]
reveal = temp
print(reveal)
Maybe not fancy but it should work:
if (guess not in [a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z]):
with my suggestion for 1.2 you would just have to check if(word==reveal): no problem with duplicate charcters.
Since I am just a hobbyist there would probably be a more professional way though.
Next time maybe splitting up your question and first looking them up individually would be better, since I am pretty sure that at least parts of your questions have been asked before.

Related

How do I fix a Stubborn syntax error in my python project?

I'm working on a school project and I've almost got it done. Doing a hangman game. for the "else:" command below print (char) on line 32 I keep getting a syntax error and nothing I've tried so far fixes it and the compiler wont tell me what the problem is besides it being a syntax error
import time
Name =input("What is your name?")
print ("Hello,"+Name,"Time to play hangman")
print( "")
#wait for 1 second
time.sleep(1)
print("Start guessing...")
time.sleep(0.5)
#here we set the secret
word = "ball"
#creates an variable with an empty value
guesses = ""
#determine the number of turns
turns =10
#create a while loop
#check if the turns are more than zero
while turns > 0:
#make a counter that starts with zero
Failed =0
#for every character in secret_word
for char in word:
if char in guesses:
print (char,)
else:
print ( "_", )
failed += 1
print ("You won")
break
print()
guess = input ("guess a character:")
guesses +=guess
if guess not in word
turns -=1
print ("Wrong")
print ("You have", turns, "more guesses")
if turns ==0:
print ("You Lose the Word was",word)

Nested While loop in hangman

I am creating a hangman game.Here are the conditions
User will be given six chances for wrong choices
If the letter was already entered, user will be notified that letter already exists (user will not be penalised for double wrong entry)
Now my question is :
I want to display the message that "user lost the game" if the number of wrong guessed letters goes to 7 and exists the loop but it is not happening
here is my code:
print("Welcome to Hangman"
"__________________")
word = "Python"
wordlist=list(word)
wordlist.sort()
print(wordlist)
print("Word's length is", len(word))
letter=" "
used_letter=[]
bad_letter=[]
guess=[]
tries=0
while len(bad_letter)<7:
while guess != wordlist or letter !="exit":
letter = input("Guess your letter:")
if letter in word and letter not in used_letter:
guess.append(letter)
print("good guess")
elif letter in used_letter:
print("letter already used")
else:
bad_letter.append(letter)
print("bad guess")
used_letter.append(letter)
tries+=1
print("You have ",6 - len(bad_letter), " tries remaining")
print(guess)
print("You have made ",tries," tries so far")
guess.sort()
print("Thank you for playing the game, you guessed in ",tries," tries.")
print("Your guessed word is", word)
print("you lost the game")
I am very new to python so i would appreciate help in basic concepts
It seems like your while len(bad_letter) < loop is never exiting because of the while loop below it which is checking for the right answer or exit entry runs forever.
What you should do is only have one master while loop which takes in a new input each time and then check to see if that input matches any of the conditions you are looking for.
You could structure it something like this:
bad_letter = []
tries = 0
found_word = False
while len(bad_letter) < 7:
letter = input("Guess your letter:")
if letter == 'exit':
break # Exit game loop
if letter in word and letter not in used_letter:
guess.append(letter)
print("good guess")
elif letter in used_letter:
print("letter already used")
else:
bad_letter.append(letter)
print("bad guess")
used_letter.append(letter)
tries+=1
print("You have ", 6 - len(bad_letter), " tries remaining")
print(guess)
print("You have made ",tries," tries so far")
guess.sort()
if guess == wordlist:
found_word = True
break # Exits the while loop
print("Thankyou for playing tha game, you guessed in ",tries," tries.")
print("Your guessed word is", word)
if found_word:
print("You won")
else:
print("you lost the game")
Solution
word = 'Zam'
guesses = []
guesses_string = ''
bad_guesses = []
chances = 6
def one_letter(message=""):
user_input = 'more than one letter'
while len(user_input) > 1 or user_input == '':
user_input = input(message)
return user_input
while chances > 0:
if sorted(word.lower()) == sorted(guesses_string.lower()):
print("\nYou guessed every letter! (" + guesses_string + ")")
break
guess = one_letter("\nGuess a letter: ")
if guess in guesses or guess in bad_guesses:
print("You already guessed the letter " + guess + ".")
continue
elif guess.lower() in word.lower():
print("Good guess " + guess + " is in the word!.")
guesses.append(guess)
guesses_string = ''.join(guesses)
print("Letters guessed: " + guesses_string)
else:
print("Sorry, " + guess + " is not in the word.")
bad_guesses.append(guess)
chances -= 1
print(str(chances) + " chances remaning.")
if chances == 0:
print("\nGame Over, You Lose.")
else:
word_guess = ''
while word_guess.lower() != word.lower():
word_guess = input("Guess the word: ('quit' to give up) ")
if word_guess.lower() == 'quit':
print("You gave up, the word was " + word.title() + "!")
break
if word_guess.lower() == word.lower():
print("\nCongratulations YOU WON! The word was "
+ word.title() + "!")
Hey there! I'm new to programming (week 2) and keep seeing these 'hangman' games popup, since today is my break from learning, I the goals you were trying to achieve and ran with it.
Added some extra features in here such as breaking the loop if the all letters are guessed, and then asking the user to guess the final word.
Notes
There is a ton of Refactoring you could do with this(almost breaks my heart to post this raw form) but I just blurted it on on the go.
Also note that my original goal was to stick to your problem of not allowing the same letter to be entered twice. So this solution only works for words that contain no duplicate letters.
Hope this helps! When I get some time I'll Refactor it and update, best of luck!
Updates
Added bad_guesses = [] allows to stop from entering bad guess twice.

print something when input isn't something specified

Sorry for the horrible question. Basically, I am making the Yes or No game in Python and I need it to print something e.g. "You Win" if they input something from a library that I have already made with every acceptable word. TY in advance
q1 = input ("Answer: ")
while q1 == "yes" or "Yes" or "no" or "No":
print ("Sorry but you answered \"" + q1 + "\" which means you lose!")
sys.exit ("\nGame Over")
if q1 == ###:
print ("Well done you have earned yourself a point")
score +=1
print ("Your current score is: " + score)
input_word = input('Insert a word: ')
list_of_acceptable_words = ['word1', 'word2']
if input_word in list_of_acceptable_words:
print('You Win')
Where input_word is a string containing the input from the user and list_of_acceptable_words is a list of acceptable words
You can probably start out from this snippet, using the built-in set type:
>>> lib={'Alice','Bob'}
>>> print('Bob' in lib)
True
>>> print('Carol' in lib)
False
Then one can add a bit of code around to match your needs more closely:
>>> guess='Dave'
>>> print(['You lose...', 'You WIN!'][guess in lib])
You lose...
>>> guess='Alice'
>>> print(['You lose...', 'You WIN!'][guess in lib])
You WIN!
Edit: now that you have updated your OP with some snippet, I can write some code more in line with your needs.
accepted=set(line.strip() for line in open('accepted.txt'))
q1 = input("Answer: ")
while q1.lower() in {"yes", "no"}:
print ("Sorry but you answered \"" + q1 + "\" which means you lose!")
sys.exit ("\nGame Over")
if q1 in accepted:
print ("Well done you have earned yourself a point")
score +=1
print ("Your current score is: " + score)
Of course, if you count good answers, you will want to put this into some loop, then the initializition of accepted can stay outside.

Unexpected EOF while Parsing In Russian Roulette

Im doing a little home project since I'm learning python (beginner) and I made my self a Russian roulette game and it comes up with Unexpected EOF while Parsing on the last line. So if some could help me out on whats going wrong I will be very thankful.
import random
print ("Welcome to Russian Roulette without guns :/ ")
amount = input("How many players? 2 or 3 or 4:")
if amount == ("2"):
print ("Player 1 Name")
player_1 = input(" ")
print ("Player 2 Name")
player_2 = input(" ")
print (player_1)
enter = input("Click Enter:")
if enter == (""):
number = random.randint(1, 2)
print (number)
if number == 1:
print (player_1)
print ("You dead")
print ("---------")
print (player_2)
print ("You win")
else:
print (player_2)
enter_2 = input("Click Enter:")
if enter_2 == (""):
number_2 = random.randint(1, 2)
if number_2 == 1:
print (player_2)
print ("You Lose")
print ("---------")
print (player_1)
print ("You win")
elif amount == ("3"):
print ("Player 1 Name")
player_1 = input(" ")
print ("Player 2 Name")
player_2 = input(" ")
print ("Player 3 Name ")
player_3 = input(" ")
print (player_1)
enter_3 = input("Click Enter:")
if enter_3 == (""):
number_3 = random.randint(1, 1)
print (number)
if number == 3:
print (player_1)
print ("You Dead")
print ("Your Out")
print ("-------------")
print ("{0}, {1} You are still in".format(player_1, player_2)
On the last line, you are missing a closing parenthesis. It should be:
print ("{0}, {1} You are still in".format(player_1, player_2))
EOF is end of file so it usually an an unexpected termination of the program, which is most likely caused by one of a few things, in python: if you missed closing parentheses, or a missing ; in the last line/ line before (so it runs as one line with out the ;). however i can tell you that you are missing closing parentheses at the end of the last print statement. also just a small improvement i would suggest, comment your code python is quite easy to read but its good practice for languages that are not as easy to read.

Why is my if true/elif/else-code not working?

In python, I am trying to make this code accept the user to move forward if he writes "True", and not if he writes "False" for the statement in User_Answer. When I run the code however, I get the "the answer is correct!"-part no matter what I write. The part I am having trouble with starts with "Test_Answer".
Could anyone help me with this?
name_list = ["Dean", "Bill", "John"]
enter_club = ["Enter", "enter"]
print ("THE CLUB - by Mads")
print (" ")
print ("""You approach a secret club called \"The club\". The club members are dangerous.
Make sure you tell the guard one of the members names.""")
print ("")
print ("Good evening. Before you are allowed to enter, we need to check if your name is on our list.")
def enter_the_club():
enter_now = input(" \nPress \"enter\" to enter the club... ")
if (enter_now in enter_club) == True:
print (" ")
print ("But as you enter, you are met with an intelegence test. \n It reads:")
check_name = input("What is your name? ")
def list_check():
if (check_name in name_list) == True:
print("Let me check.. Yes, here you are. Enjoy yourself, %s!" % check_name)
enter_the_club()
elif check_name.isalpha() == False:
print("Haha, nice try %s! Let's hear your real name." % check_name)
list_check()
elif (check_name in name_list) == None:
print ("You will need to give us your name if you want to come in.")
list_check()
else:
print ("I am sorry, but I can not find your name on the list, %s." % check_name)
print ("Are you sure that's your listed name?")
list_check()
list_check()
print ("But as you enter, you are met with an intelegence test.")
print (" ")
print ("It reads:")
Test_Answer = True
def IQtest():
User_Answer = input("Is 18/4 % 3 < 18 True or False? ")
if Test_Answer == User_Answer:
print ("Great, %s, the answer is correct!" % check_name)
else:
print ("You are not allowed to enter before the answer is correct, %s!" % check_name)
IQtest()
IQtest()
True is a boolean constant. What the user enters will be either "True" or "False", both character strings. Also, your elif condition cannot be true. What are you trying to do with three decision branches?
Without changing your code too much ... try this?
Test_Answer = "True"
def IQtest():
User_Answer = input("Is 18/4 % 3 < 18 True or False? ")
if Test_Answer == User_Answer:
print ("Great, %s, the answer is correct!" % check_name)
else:
print ("You are not allowed to enter before the answer is correct, %s!" % check_name)
IQtest()
Note that I've also corrected your "else" syntax.
Also, you have no value for check_name; I assume this is a global variable that you've handled elsewhere.

Categories