I'm making a hangman program, and I want it to be able to include phrases; however, when I input a phrase to be guessed, the output only dashes. For instance, when I put in "how are you"(input to be guessed), the output is "-----------". What i want the out put to be is "--- --- ---", as it makes it easier for the player to know that it is a phrase. I've tried a 'for' loop and 'if' statement to now avail, and would appreciate some help. Thanks!
*At the moment I'm trying replace. Also, if this is badly worded, let me know and I'll try rewriting it.
right = ""
guess=""
attempts = 6
tries = 0
space = " "
print("Hangman: guess letters until you can guess the word or phrase.")
print("In this game you get six tries.")
right_str = str(input("\nEnter your word: "))
right_str = right_str.lower()
#displays the proper amount of unknown spaces
right = right * len(right_str)
if space in right_str:
right_str.find(space, i)
print(i)
you could try this:
guess=""
attempts = 6
tries = 0
space = " "
print("Hangman: guess letters until you can guess the word or phrase.")
print("In this game you get six tries.")
right_str = str(input("\nEnter your word: "))
right_str = right_str.lower()
output = ""
for c in right_str:
if c != " ":
output += "-"
else:
output += " "
print output
Related
This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 1 year ago.
I have coded a game of Hangman. For unknown letters, it prints a _, but because it is in a while loop it prints a different line. Is there a way to put all the dashes on the same line, so it easier to read?
My code is below:
import time
import random
# Welcoming the user
name = input("What is your name? ")
print("Hello, " + name, "Time to play hangman!")
print(" ")
# Wait for 1 second
time.sleep(1)
print("Start guessing letters...")
time.sleep(0.5)
# Here we set the secret
words = ("pyhton","coding","recycle","dawn","vision","talkative","love","difficulty","late","bake","compact","old","employee","be","bubble","guess","home","urgency","buttocks","shop","fluctuation",
"snack","fling","structure","incentive","enemy","fastidious","overcharge","disagreement","consciousness")
word = random.choice(words)
# 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:
# See if the character is in the players guess
if char in guesses:
# Print then out the character
print(char)
else:
# If not found, print a dash
print("_")
# And increase the failed counter with one
failed += 1
# If failed is equal to zero
# Print "You Won"
if failed == 0:
print("You won, The word was", word)
# Exit the script
break
print
# Ask the user go guess a character
guess = input("guess a character: ")
# Set the players guess to guesses
guesses += guess
# If the guess is not found in the secret word
if guess not in word:
# Turns counter decreases with 1 (now 9)
turns -= 1
# Print "Wrong"
print("Wrong")
# How many turns are left
print("You have", + turns, 'more guesses' )
# If the turns are equal to zero
if turns == 0:
# Print "You Lose"
print("You Lose")
print("The word was",word)"
The print function has an end parameter which means you can say something like this:
print("text", end=" ")
And instead of moving to a new line, your code will print everything on the same line with spaces between every print.
Note you will have to add this to both print statements:
# see if the character is in the players guess
if char in guesses:
# print then out the character
print(char, end=" ")
else:
# if not found, print a dash
print("_", end=" ")
And you will have to add a "\n" to the front of the text that comes right after the word:
guess = input("\nguess a character: ")
This should do the trick:
Replace your print call for printing "_" with this:
print("_", end = "")
Example:
for i in range(10):
print("_", end="")
# Out: __________
If you want to change the default character at the end of print calls, use the end keyword arg. Example:
>>> word = 'python'
>>> for x in word:
... print(x, end = ' ')
...
p y t h o n
I'm still a noob when it comes to coding and I'm trying to create my own hangman game. I ran into some difficulties when it comes to guessing characters of a word which occur more than once in a word.
Here's a snippet of my code:
def random_word():
#word generator
randomized = random.randint(0,(len(content_words)-1))
word_to_guess = content_words[randomized].lower()
splitted = []
word_progress = []
for character in word_to_guess:
splitted.append(character.lower())
word_progress.append("?")
counter = 0
while counter <= 5:
print(word_to_guess)
print(splitted)
print(word_progress)
#Start of the game
options = str(input("Do you want to guess the word or the characters?: ").lower())
#word
if options == "word":
guess_word = input("Please your guess of the word: ").lower()
if guess_word == word_to_guess:
print("Correct! The word was " + word_to_guess + " you only needed " + str(counter) + " tries!")
break
elif guess_word != word_to_guess:
counter += 3
print("You have entered the wrong word ! You now have " + str(5-counter) + " tries left!")
continue
#characters
elif options == "characters":
guess_character = input("Please enter the character you would like to enter!: ")
if guess_character in splitted and len(guess_character) == 1:
print("Correct! The character " + guess_character.upper() + " is in the word were looking for!" )
for char in word_to_guess:
if char == guess_character:
word_progress[word_to_guess.index(char)] = word_to_guess[word_to_guess.index(char)]
continue
....so basically in the character section only the first occurrence of the guessed character gets implemented into the word_to_guess list. What is the best way to handle this problem?
By the way this is the first question I've ever asked regarding to coding and on this platform, please excuse me if I didn't really formulate my problem in the most efficient way.
index will only return the index of the first occurence of your character.
You should use enumerate to iterate on the characters and indices at the same time:
for index, char in enumerate(word_to_guess):
if char == guess_character:
word_progress[index] = guess_character
I have been looking around to see if I could find something that could help, but nowhere has an answer for what I'm looking for. I have a Hangman game I'm doing for a final project in one of my classes, and all I need is to make it so if a word has a capital letter, you can input a lowercase letter for it. This is the code.
import random
import urllib.request
wp = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-
type=text/plain"
response = urllib.request.urlopen(wp)
long_txt = response.read().decode()
words = long_txt.splitlines()
###########
# Methods #
###########
def Run():
dashes1 = "-" * len(word)
dashes2 = "-" * len(word2)
used_letter = []
dashes = dashes1 + " " + dashes2
#dashes ="-" * len(secretWord)
guessesLeft = 6
while guessesLeft > -1 and not dashes == secretWord:
print(used_letter)
print(dashes)
print (str(guessesLeft))
guess = input("Guess:")
used_letter.append(guess)
if len(guess) != 1:
print ("Your guess must have exactly one character!")
elif guess in secretWord:
print ("That letter is in the secret word!")
dashes = updateDashes(secretWord, dashes, guess)
else:
print ("That letter is not in the secret word!")
guessesLeft -= 1
if guessesLeft < 0:
print ("You lose. The word was: " + str(secretWord))
print(dashes)
else:
print ("Congrats! You win! The word was: " + str(secretWord))
print(dashes)
def updateDashes(secret, cur_dash, rec_guess):
result = ""
for i in range(len(secret)):
if secret[i] == rec_guess:
result = result + rec_guess
else:
result = result + cur_dash[i]
return result
########
# Main #
########
word = random.choice(words)
word2 = random.choice(words)
#print(word)
#print(word2)
secretWord = word + " " + word2 # can comment out the + word2 to do one
word or add more above to create and combine more words will have to adjust
abouve in Run()
splitw = ([secretWord[i:i+1] for i in range(0, len(secretWord), 1)])
print (splitw)
Run()
any bit of help is appreciated. The website I'm using has a bunch of words that are being used for the words randomly generated. Some are capitalized, and I need to figure out how to let the input of a letter, say a capital A, accept a lowercase a and count for it.
you could compare after you converted everything to lowercase.
e.g. you could do
secretWord = word.lower() + " " + word2.lower() # that should make your secret all lowercase
for the input you should do the same:
guess = input("Guess:").lower()
after that it should not matter if it is upper or lower case. it should always match if the letter is the correct one.
hope that helps
Simply check everything in lowercase:
[...]
elif guess.lower() in secretWord.lower():
[...]
and so on.
I would just change this line:
while guessesLeft > -1 and not dashes == secretWord:
to:
while guessesLeft > -1 and not dashes.lower() == secretWord.lower():
This way you are always comparing lower-case representations of the user's input to the lower-case representation of your secretWord. Since this is the main loop for your game, you want to break out of this as soon as the user's guess matches your word regardless of case. Then later in your code, you will still check whether they had any guesses left, and print out their answer and the secret word as before.
No other changes required, I think.
You could just force all comparisons to be made in the same Case, such as lowercase.
Let’s say that your word is "Bacon". and someone enters "o".
That will be a match because quite obviously “o” equals “o” so you can cross that letter off the list of letters left to guess.
But in the case that someone enters “b” then b is NOT equal to “B”.
So why not just force all letters to be compared using the same case?
So your comparison will be like
elif guess.Lower() in secretWord.Lower()
My python is rusty as hell, but the idea here should do what you want to do
I'm having trouble with this hangman coding. When I run the code, it asks the question "Type in a letter a - z", but when I type in a letter, instead of it putting a letter, it just ask the same question from the beginning without letting me know if the letter is correct or not.
import random
possibleAnswers = ["page","computer","cookie","phishing","motherboard","freeware","bus","unix","document","hypertext","node","digital","worm","macro","binary","podcast","paste","virus","toolbar","browser"]
random.shuffle(possibleAnswers)
answers = list(possibleAnswers[1])
display = []
display.extend(answers)
for i in range(len(display)):
display[i] = "_"
print ' '.join(display)
print "\n\n\n\n"
count = 0
while count < len(answers):
guess = raw_input("Type in a letter a - z: ")
guess = guess.upper()
for i in range(len(answers)):
if answers[i] == guess:
display[i] = guess
count += 1
print ' '.join(display)
print "\n\n\n"
It does tell you, after a fashion. The problem is that your entire word list is lower-case, but you specifically change all of your input guesses to upper-case. Those cannot match, so there's never a "correct" guess. Change the word list to capitals, or change your conversion from upper to lower.
I'm in a basic programming class and I'm a bit stuck working on this game. The idea was to create a simple word-guessing game, where the computer would choose a random word and you would attempt to guess first some letter in the word, then the word itself after 5 tries. I've gone through multiple times and I still get an error of "Invalid Syntax" when I attempt to run the module.
I'm a bit dyslexic when it comes to programming languages, so maybe there's something I'm overlooking?
I would appreciate it if someone out there could offer a bit of help!
#Word Guessing Game
#Computer picks a random word
#Player tries to guess it
#computer only responds with yes or no
import random
tries = 0
print "Welcome to the word game!"
print "\nI'm going to think of a word and you have to guess it!"
print "\nGuess which letters are in the word, then you have to guess the whole thing!"
print "\nGood luck!"
WORDS = ("follow", "waking", "insane", "chilly", "massive",
"ancient", "zebra", "logical", "never", "nice")
word = random.choice(WORDS)
correct = word
length = len(word)
length = str(length)
guess = raw_input("The word is " + length + " letters long. Guess a letter!: ")
while tries < 5:
for guess in word:
if guess not in word:
print "Sorry, try again."
else:
print "Good job! Guess another!"
tries = tries + 1 #*
if tries = 5:
final = raw_input ("Try to guess the word!: ")
if final = correct:
print "Amazing! My word was ", word, "!"
else:
print "Sorry. My word was ", word, ". Better luck next time!"
raw_input("\n\nPress enter to exit")
It should also be noted that the problems occurred after the end of the "while tries" block, when I attempted to specify the limits of the "tries" variable. I've worked with it before in a random number game, but for some reason it didn't work properly here. I would greatly appreciate some help!
It should also be noted that I run on a rather outdated version of Python, some variation of 2.0, I believe.
tries = tries + 1
if tries == 5:
final = raw_input ("Try to guess the word!: ")
if final == correct:
You need == for comparison not =, = is for assignment.
You can also replace tries = tries + 1 with tries += 1
You also want to move raw_input inside the loop and just ask the user to guess the word outside the while when the guesses are all used up:
while tries < 5:
guess = raw_input("The word is " + length + " letters long. Guess a letter!: ")
if guess not in word: # use `in` to check if the guess/letter is in the word
print "Sorry, try again."
else:
print "Good job! Guess another!"
tries += 1
# guesses are all used up when we get here
final = raw_input ("Try to guess the word!: ")
if final == correct:
print "Amazing! My word was ", word, "!"
else:
print "Sorry. My word was ", word, ". Better luck next time!"
please try this one.
import random
index = -1
infi = ("python","jumble","hide","mama")
word = random.choice(infi)
word_len = len(word)
guess = ""
attempt = 0
enter = ""
print(word)
temp = "_" * word_len
print("\t\t The word chosen by computer contain", word_len,"letters.")
print("\t Tap any letter to check if this letter is in computer word.\n")
print("\t You got 5 attempts to check if tapped letter is in computer word.\n")
print("\t\t\t\t GOOD LUCK!!!\n\n\n\n")
for i in range(0, 5):
attempt +=1
guess = input("Attempt no. "+str(attempt)+":")
if guess in word and guess != enter:
for i in range(0, word_len):
if guess == word[i]:
temp = temp[:i] + guess +temp[i+1:]
print("yes\n" + temp)
if guess not in word:
print("no")
if "_" not in temp:
print("\t\t*********** Congratulation!! You guess the word *************")
break
elif attempt == 5:
guess = input("And the word is:")
if guess == word:
print("\t\t*********** Congratulation!! You guess the word *************")
else:
print("\t\t*********** WRONG!! Shame on you *************")