I'm going over the formatting of the while loop and I remain unsure (I'm a beginner- forgive me) of how I can go about fixing this. Any assistance would be greatly appreciated! I do not want the 'Sorry that's not it' message to pop up when the user asks for a hint- and yet it persists in doing just that.
# Word Jumble
#
# The computer picks a random word and then "jumbles" it
# The player has to guess the original word
import random
# create a sequence of words to choose from
WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone")
# pick one word randomly from the sequence
word = random.choice(WORDS)
hint = ''
if word == 'python':
hint = 'snake'
if word == 'jumble':
hint = 'jumble'
if word == 'easy':
hint = 'opposite of hard'
if word == 'difficult':
hint = 'opposite of easy'
if word == 'answer':
hint = 'question'
if word == 'xylophone':
hint = 'dingding'
# create a variable to use later to see if the guess is correct
correct = word
# create a jumbled version of the word
jumble =""
while word:
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[(position + 1):]
count = 0
# start the game
print(
"""
Welcome to Word Jumble!
Unscramble the letters to make a word.
(Press the enter key at the prompt to quit.)
"""
)
print("The jumble is:", jumble)
guess = input("\nYour guess: ")
while guess != correct and guess != "":
print("Sorry, that's not it.")
count += 1
hint_input = input('would you like a hint')
if hint_input == 'y':
print(hint)
else:
guess = input("Your guess: ")
if guess == correct:
print("That's it! You guessed it!\n")
print("Thanks for playing.")
input("\n\nPress the enter key to exit.")
Remove the else: since you always wish to get a new guess from the user, regardless of if they've received a hint.
if hint_input == 'y':
print(hint)
guess = input("Your guess: ")
Your code works fine - but you are expected to enter a string including the " or ' in the input field. So enter "jumble" and not just jumble or "y" and not just y.
(well, there is some strange logic in there, e.g. after giving a hint it asks once more whether you want a hint - jus remove the else to get rid of this behaviour) but at least it works...)
I've copied your code and ran it.
I changed input to raw_input, which makes input much nicer.
Removed else: after print(hint) , which should fix your problem.
Lastly, I've added extra space after "Would you like a hint? " - makes it a bit easier to read.
# Word Jumble
#
# The computer picks a random word and then "jumbles" it
# The player has to guess the original word
import random
# create a sequence of words to choose from
WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone")
# pick one word randomly from the sequence
word = random.choice(WORDS)
hint = ''
if word == 'python':
hint = 'snake'
if word == 'jumble':
hint = 'jumble'
if word == 'easy':
hint = 'opposite of hard'
if word == 'difficult':
hint = 'opposite of easy'
if word == 'answer':
hint = 'question'
if word == 'xylophone':
hint = 'dingding'
# create a variable to use later to see if the guess is correct
correct = word
# create a jumbled version of the word
jumble =""
while word:
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[(position + 1):]
count = 0
# start the game
print(
"""
Welcome to Word Jumble!
Unscramble the letters to make a word.
(Press the enter key at the prompt to quit.)
"""
)
print("The jumble is:", jumble)
guess = raw_input("\nYour guess: ")
while guess != correct and guess != "":
print("Sorry, that's not it.")
count += 1
hint_input = raw_input('would you like a hint? ')
if hint_input == 'y':
print(hint)
guess = raw_input("Your guess: ")
if guess == correct:
print("That's it! You guessed it!\n")
print("Thanks for playing.")
raw_input("\n\nPress the enter key to exit.")
Related
import random
title = ("Guess the Word Title")
print(title.center(80))
Tuple = ()
Tuple = ("Spring", "Summer", "Autumn", "Winter")
TupleItem = random.choice(Tuple)
Item_len = len(TupleItem)
ItemAsteriks = ("*" * Item_len)
print("\n\n\n", ItemAsteriks.center(80), "\n\n\n")
response = "n"
while response == "n":
response = input("Would you like to guess the word (y / n)? ")
if response == "y":
break
letter = input("\nEnter a letter: ")
if letter.upper() in TupleItem.upper():
print("The letter ", letter, "is in the word!\n")
new_message = ""
for i in range(len(TupleItem)):
if TupleItem[i].upper()==letter.upper():
new_message += TupleItem[i]
else:
new_message += ItemAsteriks[i]
ItemAskeriks = new_message
else:
print("The letter ", letter, "is not in the word!\n")
GuessedWord = input("\nGuess the word then: ")
if GuessedWord.upper() == TupleItem.upper():
print("You guessed the right word. Congratz!")
else:
print("You guessed the wrong word. The right word was:", TupleItem)
input("\n\nPress Enter to Exit. ")
This is what i've come up so far. If the word is "Summer" and user guessed letter "U", I want to show/update the asterisks like: *u****., and so on. I tried some print commands under the for loop but i couldnt figure it out.
Well, I think the problem is that it will always just show the most recent letter, but not the ones from before. I would initialise a list of strings, one for each letter in the word, starting with
guessed = ["*"] * len(TupleItem)
Then at each guess, iterate though the real word and replace * entries with the actual guessed letter.
for k, ch in enumerate(TupleItem.upper()):
if ch == letter.upper():
guessed[k] = ch
Then you can simply
print("".join(guessed))
I have provided a list of words that will randomly be picked for the game. What it does is to prompt the player to enter an alphabet of the selected word. If the letter provided by the users is found in the selected word, they if be asked if they want to attempt spelling the whole word. if they say yes, then they will be able to do so. Else, they will have to try entering another alphabet.how do I get the output/ results of each user input to be printed as (eg: Outcome: a------) And if the users ended up saying yes to spelling the whole word, how should they be prompt to enter the word?
eg: Do you want spell the word now? (y/n): y
Spell the complete word:
You are correct!
The correct word is albumen
Spell another word? (y/n): y
import random
wordList = ('apple', 'albumen', 'toothpaste', 'enthusiastic')
word = random.choice(wordList)
letter_guess = ""
word_guess = ""
store_letter = ""
count = 1
limit = 5
countLetters = len(word)
choice1 = ("Do you want to spell the word now? (y/n):")
choice2 = ("Spell another word? (y/n):")
choiceY = ("y")
choiceN = ("n")
startGame = print("The word ________ has {} letters. Spell it in 5 tries.".format(countLetters))
while count < limit:
letter_guess = input("Try {} - Current: ________. Your guess? ".format(count))
if letter_guess in word:
print ("yes")
print (input(choice1))
else :
print("no")
count += 1
if choice1 == choiceY:
print (input("Spell the complete word: "))
else:
print (letter_guess)
store_letter += letter_guess
count += 1
while count == limit:
spellFinal = input("Spell the complete word: ")
if spellFinal in word:
print ("You are correct!")
print ("Spell another word? (y/n):")
if choice == "y":
print (startGame)
else:
print('Remaining Words are: ', store_letter)
if spellFinal not in word:
print ("You are incorrect")
print ("The correct word is {}.".format(correct))
You are not collecting the information from your print (input(choice1)) line. You should be assigning it to a variable to be able to compare it later with your choiceY (or you could simply compare the new variable to "y" without having a choiceY variable defined, up to you).
For example:
user_choice = ""
complete_word = ""
if letter_guess in word:
print ("yes\n")
user_choice = input(choice1)
if user_choice.lower() is "y":
complete_word = input("Spell the complete word: ")
#here you compare complete_word with your word variable
else:
print (letter_guess)
store_letter += letter_guess
count += 1
else:
print("no\n")
count +=1
The same applies to the other sections of you code that have the print(input(...)).
Nested ifs can get messy. Perhaps you can consider having a verification function and call that instead.
Hope this helps!
How do I end this game? If the whole word is guessed it's over or you loose all life, but I am unable to end it if someone guesses all letters one by one.
secret_word = "something".upper()
lifes = u'\u2764'
total_lifes = 5
print("You have 5 lifes in total to guess the answer")
guess = None
for_list = "?"*len(secret_word)
my_list = list(for_list)
def change_user_output(value):
for j in range(0, len(secret_word)):
if (value == secret_word[j]):
my_list[j] = value
new_user_output = " ".join(my_list)
print(new_user_output)
while total_lifes > 0:
print(lifes * total_lifes)
print("Guess any letter : ")
guess = input().upper()
if(guess == secret_word):
print("WOW that is correct, the secret word is %s"%secret_word)
break
if(guess in secret_word):
print("You guessed it right %s is in SECRET WORD"%guess)
change_user_output(guess)
else:
print("There is no such letter in the SECRET WORD, you loose a life")
change_user_output(guess)
total_lifes -= 1
if total_lifes == 0:
print("You've lost all lifes, GAME OVER FOR YOU")
print("The SECRET WORD was : %s"%"".join(secret_word))
The problem is that if (guess == secret_word): will always be False since guess is a single letter and it gets replaced by a new input every iteration guess = input().upper(). So your loop will never quit in case of correct guess, it will quit only when you finish the lives.
You could add the following to check if the guessed letters match those in the secret word:
if(guess in secret_word):
print("You guessed it right %s is in SECRET WORD"%guess)
change_user_output(guess)
# New code below here.
if set(list(secret_word)) == set(my_list):
print("WOW that is correct, the secret word is %s"%secret_word)
break
You create a set of all letters needed. You add each guessed letter to another set.
If the set of needed letters is a subset of the guessed letters set, you are done:
secret_word = "apple".upper()
lifes = '#'
total_lifes = 5
print("You have 5 lifes in total to guess the answer")
guess = None
for_list = "?"*len(secret_word)
my_list = list(for_list)
characters_needed = set(secret_word) # set of all letters needed
characters_guessed = set() # set of guessed letters
len_secret = len(secret_word)
def change_user_output(value):
for j in range(0, len(secret_word)):
if (value == secret_word[j]):
my_list[j] = value
new_user_output = " ".join(my_list)
print(new_user_output)
while total_lifes > 0:
print(lifes * total_lifes)
print("Guess any letter : ")
guess = input().upper()
# check for correct lenghts of input:
if len(guess) not in (1,len_secret):
print("1 letter or the whole word! Try again.")
continue
if(guess == secret_word):
print("WOW that is correct, the secret word is {}".format(secret_word))
elif(len(guess) > 1):
print("Thats not the SECRET WORD.")
total_lifes -= 1
continue
# if you input a whole word, this will decrease the lives
# as no multiletter-input can be in your set of characters
if(guess in characters_needed):
print("You guessed it right {} is in SECRET WORD".format(guess))
characters_guessed.add(guess)
change_user_output(guess)
else:
print("There is no such letter in the SECRET WORD, you loose a life")
change_user_output(guess)
total_lifes -= 1
if (characters_needed.issubset(characters_guessed)):
print("You guessed all the characters. The secret word is {}".format(secret_word))
break
if total_lifes == 0:
print("You've lost all lifes, GAME OVER FOR YOU")
print("The SECRET WORD was : %s"%"".join(secret_word))
Output (for a,p,l,e):
#####
Guess any letter : a
You guessed it right A is in SECRET WORD
A ? ? ? ?
#####
Guess any letter : p
You guessed it right P is in SECRET WORD
A P P ? ?
#####
Guess any letter : l
You guessed it right L is in SECRET WORD
A P P L ?
#####
Guess any letter : e
You guessed it right E is in SECRET WORD
A P P L E
You guessed all the characgters. The secret word is APPLE
I also added some safeguarding around allowing whole word or 1 character to be inputted.
I have been stuck on this for a while now and I can't figure out what to do. I know that it will probably involve creating an empty list and then adding the words to the list but I haven't got a clue when it comes to retrieving the words as I have never done this before.
the code itself works, it's just adding this new function I'm having trouble with.
import random
import sys
#importing both random and time modules
print("Hello!")
playAgn = 'yes'
animalNames = ['wildebeest','wolverine','woodlouse','woodpecker','yak','zebra']
#this is the list of words that the user will have to guess if they play the game multiple times
while playAgn == 'yes':
secretWord = random.choice(animalNames)
#this line tells the computer to randomly select one of the words in the list "animalNames"
lives = 6
#Defining how many lives the user has
guessedletters = []
print("Okay!\n Lets play hangman!!")
while lives > 0:
inword = False
#user has not guessed word yet so the boolean value is automatically off (False)
print("you have",lives, "lives")
#tells the user how many lives they have left
guessedletter = input("Guess a letter: ")
if len(guessedletter) > 1:
print("Error! Please only enter 1 letter at a time")
#if the user tries to guess something longer than 1 character the computer displays a message asking to only enter 1 letter at a time
elif guessedletter in guessedletters:
print("Sorry, you have already guessed this letter. Try again")
#if the user tries to guess a letter that has already been guessed the computer displays a message telling the user to choose another letter as they have already chose this one
else:
guessedletters+=str(guessedletter)
#adds the guessed letter to guessedletters variable
print("You have guessed:")
for letter in guessedletters:
print(letter.upper(),"")
#prints the letters already guessed in uppercase
shownword = ""
for letter in secretWord:
if letter in guessedletters:
shownword +=str(letter)
#if the letter is in guessedletters then add the letter to shownword(word displayed to user)
if letter == guessedletter:
inword = True
#inword is true as the guessed letter is in the secret word
else:
shownword+=str("_")
#the computer is now adding the underscores too the word being displayed to the user
print(shownword)
#the computer prints the word with the letters that the user has guessed so far (word including underscores for not yet guessed characters)
if "_" not in shownword:
print("Congratulations, you won! The word was '", shownword,"'")
#if there are no underscores(meaning the word is completed) tell the user they have won the game
break
elif inword == False:
#the guessed word is not in the secret word so the boolean value is now off (False)
print("No luck," , guessedletter , "is not in my word")
lives -= 1
#deducts a life for the wrong letter being guessed and also displays a message telling the user that the letter just guessed isn't in the secret word
if lives == 0:
print("You have run out of lives. The word was '",secretWord,"'")
#if the user runs out of lives and still hasn't guessed the word, tell them they failed to beat the game and also tell them the word
while True:
playAgn = input("Would you like to play again? yes/no: ")
if playAgn == 'no':
print("okay\n Goodbye!")
break
elif playAgn == 'yes':
break
thanks a lot to anyone who can help figure this out :)
You could just swap this:
animalNames = ['wildebeest','wolverine','woodlouse','woodpecker','yak','zebra']
For this:
animalNames = getNames()
And define the function:
def getNames():
names = []
while True:
name = raw_input("Add a word to the list (or press enter to cancel): ")
if name == "":
break
else:
names.append(name)
return names
Look at this line:
animal_names.append(input("Enter Word To Word Pool:"))
like that?
How can i run a loop within a loop in python to make points in a simple word game
import random
WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone", "truck", "doom", "mayonase", "flying", "magic", "mine", "bugle")
play = "Yes"
points = 0
ask = ('Yes')
word = random.choice(WORDS)
while play == "Yes":
hint = word
correct = word
jumble = ""
while word:
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[(position + 1):]
print(
"""
Welcome to Word Jumble!
Unscramble the letters to make a word.
(Press the enter key at the prompt to quit.)
"""
)
print("The jumble is:", jumble)
guess = input("\nYour guess: ")
while guess != correct and guess != "":
print("Sorry, that's not it.")
guess = input("Your guess: ")
print("Do you want a hint")
if ask == "yes":
print(word)
points - 10
print(points)
if guess == correct:
print("That's it! You guessed it!\n")
play = input("Do you want to play again")
points + 100
print(points)
print("Thanks for playing.")
input("\n\nPress the enter key to exit.")
is all the code i have im trying to add a point system into it. The problem im trying to do is "Improve “Word Jumble” so that each word is paired with a hint. The player should be able to see the hint if he or she is stuck. Add a scoring system that rewards players who solve a jumble without asking for the hint."
Came up with something like this... needs a lot of work, but it will set you on the right track (I hope so!!)
Here's the modified code:
import random
WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone", "truck", "doom", "mayonase", "flying", "magic", "mine", "bugle")
play = "Yes"
points = 0
ask = ('Yes')
word = random.choice(WORDS)
while play == "Yes":
next_hint = 4
hint = "{}...".format(word[0:next_hint])
correct = word
jumble = ""
while word:
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[(position + 1):]
print(
"""
Welcome to Word Jumble!
Unscramble the letters to make a word.
(Press the enter key at the prompt to quit.)
"""
)
print("The jumble is:", jumble)
guess = input("\nYour guess: ")
while guess != correct and guess != "":
print("Sorry, that's not it.")
if hint != word:
ask = input("Do you want a hint? yes / no: ")
if ask in ("yes", "y", "yeah"):
print(hint)
next_hint += 1
hint = "{}...".format(correct[0:next_hint])
points -= 10
print("You lose 10 points!")
guess = input("Your guess: ")
if guess == correct:
print("That's it! You guessed it!\n")
play = input("Do you want to play again? yes/no: ")
points += 100
print("You earn {} points!".format(points))
print("Thanks for playing.")
input("\n\nPress the enter key to exit.")
I added hints that will gradually show the word and fixed the point system (Or at least it takes into account how many hints you used).
The problem is, I always show at least 4 characters of the string and some words are that short (you'll have to fix that)
Hope it helps!!!