Right sorry, heres the code
level_1 = "The _1_ man in the _2_ place can make all the _3_ in the _4_"
level_2 = "We both _1_ a lot of _2_ that you're going to _3_. But I _4_ \ we
can put our _5_ behind us. For science. " \
"You _6_ "
level_3 = "Everyone I have _1_ for has either _2_ or left me._3_ f***ing
except for \ _4_! So don't _5_ me I'd be _6_ " \
"with somebody else, because the _7_ is I would just be more _8_ "
blank_words = ["_1_", "_2_", "_3_", "_4_", "_5_", "_6_", "_7_", "_8_", ]
level_1_answers = ["right", "wrong", "difference", "world"]
level_2_answers = ["said", "things", "regret", "think", "differences",
"monster"]
level_3_answers = ["cared", "died", "everyone", "you", "tell", "safer",
"truth", "scared"]
def level_selector():
"""Gets input from the user to see which level the game starts on"""
while True:
try:
level = int(raw_input("There are 3 levels, pick which to start
with \n -->"))
except ValueError:
print "Please select a NUMBER"
else:
if 1 <= level <= 3:
if level == 1:
return level_1, level_1_answers, level
elif level == 2:
return level_2, level_2_answers, level
elif level == 3:
return level_3, level_3_answers, level
else:
print "Select a number within the level range"
def blanks_to_fill(word, blanks):
for blank in blanks:
if blank in word:
return blank
return None
def fill_blanks(word, replaced, blanks, user_input, index):
if blanks_to_fill(word, blanks) is None:
if word not in replaced:
replaced.append(word)
else:
replacement = blanks_to_fill(word, blanks)
word = word.replace(replacement, user_input.upper())
if replacement == blanks[index]:
if replacement not in replaced:
replaced.append(word)
else:
position = replaced.index(replacement)
replaced[position] = word
else:
replaced.append(replacement)
return replaced
def format_answers(quote, blanks, replaced, user_input, index):
split_quote = quote.split()
if type(replaced) == str:
replaced = replaced.split()
for word in split_quote:
fill_blanks(word, replaced, blanks, user_input, index)
replaced = " ".join(replaced)
return replaced
def user_answer(level, quote, answers):
replaced = []
user_input = ""
index = 0
blank_range = len(answers)
for blank in blank_words[:blank_range]:
prompt = "Fill the blank for " + blank
print prompt
user_input = raw_input("-->")
user_input = user_input.lower()
while user_input != answers[index]:
print "Incorrect, please try again."
user_input = raw_input("-->")
user_input = user_input.lower()
print "Good job!"
replaced = format_answers(quote, blank_words, replaced, user_input,
index)
print replaced
index += 1
return replaced, index
def play_again():
user_response = raw_input("Would you like to play again, yes or
no?").lower()
if user_response.startswith("y"):
play()
else:
pass
def play():
quote, answers, level = level_selector()
print quote
replaced = user_answer(level, quote, answers)
print "Well done, you finished the level"
play_again()
play()
The output I'm meant to get is the quote from the selected level with the correct response from the player. Instead I'm getting an output like http://i.imgur.com/ESAOFBB.png where words are missing and the "blank" placeholders are being tagged on the end of the output. From what I can see the problem is either in the "fill_blanks" or the "format_answers" functions but I can't see it myself.
Perhaps a fresh pair of eyes can shed some light.
Greatly appreciated if you do respond, I've tried for the most part to do it myself, but I just hit a brick wall
Related
I'm new to StackOverflow (1st time posting) and new to coding with python. Currently enrolled in a course through Udacity. I'm having a very hard time with a project we were given for this course and decided to come here to see if anyone could help.
The project is to create a quiz with 4 blanks that need to be answered correctly by the player. It's required to have the quiz print out with the correct answer, but I'm having a very hard time getting this to print out correctly.
My code is below. Would appreciate any help or advice I can get on this.
Thanks!
easy_quiz = "If you ever get stuck, check out the __1__ for common
problems students face when attempting this project. If you need
additional help, you can schedule a 1:1 appointment with one of our
__2__ to get you un-stuck. This project should be __3__. If at any time
it becomes not fun, take a step back, deep breath, and ask for __4__!.
\n\n"
easy_answers = ["forums", "mentors", "fun", "help"]
medium_quiz = "Game must have 3 or more levels and each level contains 4 or more __1__ to fill in. Immediately after running the program, user is prompted to select a difficulty level from easy / __2__ / hard. Once a level is selected, game displays a fill-in-the-blank and a prompt to fill in the first one. When player guesses __3__, new prompt shows with correct answer in the previous blank and a new prompt for the next blank. When player guesses __4__, they are prompted to try again. \n"
medium_answers = ["blanks", "medium", "correctly", "incorrectly"]
hard_quiz = "__1__ are used as __2__ to automate tasks which are likely to be repeated. Functions produce the appropriate output (typically with a __3__ statement) from the appropriate input (function parameters). Your code should take advantage of __4__ and variable names should reflect the values they store. \n"
hard_answers = ["Functions", "tools", "return", "variables"]
blanks = ["__1__", "__2__", "__3__", "__4__"]
difficulty = raw_input("\nChoose your difficuty level = easy, medium, or hard? ")
print ""
if difficulty == "easy":
quiz = easy_quiz
answers = easy_answers
print "You chose easy!\n\nYou will have 5 guesses to fill in each blank. Good Luck!!\n \n" + easy_quiz
elif difficulty == "medium":
quiz = medium_quiz
answers = medium_answers
print "You chose medium!\n\nYou will have 5 guesses to fill in each blank. Good Luck!!\n \n" + medium_quiz
elif difficulty == "hard":
quiz = hard_quiz
answers = hard_answers
print "You chose hard!\n\nYou will have 5 guesses to fill in each blank. Good Luck!!\n \n" + hard_quiz
def word_in_pos(word, parts_of_speech):
for pos in parts_of_speech:
if pos in word:
return pos
return None
def play_game(quiz, parts_of_speech):
replaced = []
i = 0
quiz = quiz.split()
for word in quiz:
replacement = word_in_pos(word, parts_of_speech)
if replacement != None:
user_input = raw_input("Type an answer for: " + replacement + " " )
word = word.replace(replacement, user_input)
replaced.append(word)
guesses = 0
while user_input != answers[i]:
guesses = guesses + 1
print "Incorrect, try again \n" + " ".join(replaced)
user_input = raw_input("Type an answer for: " + replacement + " ")
if guesses == 4:
return "\nGame Over! Better luck next time. \n"
print "Correct \n" + " ".join(replaced)
i = i + 1
word = word.replace(replacement, user_input)
replaced.append(word)
else:
replaced.append(word)
replaced = " ".join(replaced)
return replaced
print play_game(quiz, blanks)
Here is a working version of your play_game() method:
def play_game(quiz, parts_of_speech):
replaced = []
i = 0
quiz = quiz.split()
for word in quiz:
replacement = word_in_pos(word, parts_of_speech)
if replacement is not None:
user_input = raw_input("Type an answer for: " + replacement + " " )
guesses = 0
while user_input != answers[i]:
guesses = guesses + 1
if guesses == 5:
return "\nGame Over! Better luck next time. \n"
print "Incorrect, try again \n" + " ".join(replaced) + " " + replacement
user_input = raw_input("Type an answer for: " + replacement + " ")
replaced.append(user_input)
print "Correct \n" + " ".join(replaced)
i = i + 1
else:
replaced.append(word)
replaced = " ".join(replaced)
return replaced
The main change is to delay modifying the replaced list until the correct answer has been given. That simplifies a lot of the code, eliminating the need for the word variable.
Hi I have this project of Mad libs but I donĀ“t know how to make a function that ask the user what level of difficulty between easy, medium or hard they want, and depending on their answer redirect them to the desired level of mad libs. This is what I have so far. Thanks.
parts_of_speech_words = ["VERB","PLACE","ADJECTIVE","NOUN","PLURALNOUN","ADVERB"]
level_easy = """I __VERB__ to go to the __PLACE__
but I don't go in the __ADJECTIVE__
I am __ADJECTIVE__ of the __NOUN__
and getting __VERB__ by a __NOUN__."""
level_medium = """Begging to hear __NOUN__
My ears remain __ADJECTIVE__
__NOUN__ for signs
my __NOUN__ remain __VERB__
Yet __NOUN__still VERB."""
level_hard = """I __VERB__ you without __NOUN__
how, or when, or from where,
I love you __ADVERB__,
without __PLURALNOUN__ or pride;
So I love you because I know
no other way that this:
Where I does not VERB, nor you,
so close that your NOUN
on my chest is my hand,
so close that your NOUN close
as I fall ADJECTIVE."""
greeting = raw_input ("Welcome to mad libs, What's your name? ")
prompt = raw_input ("Select your level: easy, medium or hard: ")
def entry_level_prompt (variable_level):
easy = level_easy
medium = level_medium
hard = level_hard
for e in variable_level:
if prompt == easy:
return level_easy
print level_easy
if prompt == medium:
return level_medium
print level_medium
if prompt == hard:
return level_hard
print lever_hard
print "Ok %s you chose the %s level" % (greeting , prompt)
print entry_level_prompt (variable_level)
def parts_of_speech (words_string, list_of_part_of_speech):
for pos in list_of_part_of_speech:
if pos in words_string:
return pos
return None
def play_mad_libs (split_string, list_of_part_of_speech):
replaced = []
split_string = split_string.split ()
for words_string in split_string:
replacement = parts_of_speech (words_string, list_of_part_of_speech)
if replacement != None:
user_input = raw_input ("Type in a: " + replacement + " ")
words_string = words_string.replace (replacement, user_input)
replaced.append(words_string)
else:
replaced.append(words_string)
replaced = " ".join(replaced)
return replaced
print play_mad_libs (entry_level_prompt, parts_of_speech_words)
You have a bug in your code. You are calling entry_level_prompt(variable_level) but variable_level does not exist outside of the method scope.
To control the difficulty, you can create a method called get_difficulty()
def get_difficulty():
choice = ""
while choice not in ('easy', 'medium', 'hard'):
choice = raw_input("choose your difficulty: ")
if choice == "easy":
return level_easy
elif choice == "medium":
return level_medium
elif choice == "hard":
return level_hard
else:
print("Invalid choice...")
You've confused the selector -- "easy", "medium", or "hard" -- with the variable you want to return -- level_easy, level_medium, or level_hard. You cannot use the variable prompt for both purposes at the same time.
I recommend that you keep variable prompt as you started: it holds the user input. Then, simply test it and return the needed script:
if prompt == "easy":
return level_easy
elif prompt == "medium"
return level_medium
elif prompt == "hard"
return level_hard
else:
"Please enter easy, medium, or hard for the level."
I'm writing a text adventure (does anyone remember Zork?), and I'm having troubles with this code:
from random import randint
def prompt():
action = input(">>> ").lower()
if action == "exit":
quit()
elif action == "save":
save()
else:
return action
def action_error(custom=False):
if custom != False:
print(custom)
else:
phrases = ["A bunch", "of funny", "error phrases"]
print(phrases[randint(1, len(phrases)-1)])
return prompt()
action = prompt()
while True:
print(action) #Debugging purposes
if action.find("switch") != -1:
if action.find("light") != -1:
second_room() #Story continues
else:
action = action_error("What do you want to switch?")
action = action_error()
The matter is that if I enter a string that contains "switch", the next input is not picked up.
Also, anyone has better ways to parse verb-noun strings like "switch the light", "open the door" or "look around"/"look at OBJECT"?
First of all I noticed that if you enter switch twice the second time it's caught as an error by your program.
I think the problem lies at the end of the action_error function where you assign the return value to prompt(), so the input get consumed too early.
A possible fix would be:
def action_error(custom=False):
if custom != False:
print(custom)
else:
phrases = ["A bunch", "of funny", "error phrases"]
print(phrases[randint(1, len(phrases)-1)])
while True:
action = prompt()
print(action) #Debugging purposes
if action.find("switch") != -1:
if action.find("light") != -1:
second_room() #Story continues
else:
action_error("What do you want to switch?")
else:
action_error()
So no return value for action_error() and direct assignment at the beginning of the while loop.
How about, in the case of a partially entered compound action, you concatenate the new input to the old one? Then "switch" becomes "switch light", and both of your conditionals will pass.
action = prompt()
while True:
print(action) #Debugging purposes
if action.find("switch") != -1:
if action.find("light") != -1:
second_room() #Story continues
else:
action = action + " " + action_error("What do you want to switch?")
continue
action = action_error()
Bonus style suggestions:
replace a.find("b") != -1 with "b" in a
use random.choice(phrases) instead of phrases[randint(1, len(phrases)-1)]
I need to replace 1 symbol in a string with a letter, like a decoder game, but with the code I have currently created. I need to develop the part of the program that when someone inputs a symbol and a letter it replaces the symbol with the letter and saves the list, then you keep doing this untill all the symbols have been replaced to create a word.
The list of encoded words:
#+/084&"
#3*#%#+
8%203:
,1$&
!-*%
.#7&33&
#*#71%
&-&641'2
#))85
9&330*
The List of words uncoded:
ACQUIRED
ALMANAC
INSULT
JOKE
HYMN
GAZELLE
AMAZON
EYEBROWS
AFFIX
VELLUM
Clues:
A#
M*
N%
Code:
#Import Section
import random
import string
class Game():
def __init__(self):
words_open = open('Words.txt')
self.words = (words_open.read())
self.fixwords = self.words
solved_open = open('solved.txt')
self.solved = (solved_open.read())
def menu_display(self):
#Display the menu
self.menud = (''' MENU
1. Start Game
2. Quit Game
Please select 1 or 2''')
self.menu()
def menu(self):
print self.menud
#ask player to choose an option
self.menu_choice = raw_input(" >>> ")
print
self.menu_options()
def menu_options(self):
#When menu option is selected
if self.menu_choice == '1':
self.s_game()
elif self.menu_choice == '2':
pass
else:
print "not valid input"
self.menu()
def s_game(self):
print 'Words:'
print self.words
self.clues()
def clues(self):
clue = raw_input('Do you want clues? please enter Yes or No '
'>>> ')
clue = clue.upper()
print clue
clues_open = open('clues.txt')
self.cluesclues = (clues_open.read())
if clue == 'YES':
print '''Words:
'''
print self.words
print 'Clues:'
print self.cluesclues
self.sorting()
elif clue == 'NO':
print self.words
self.sorting()
else:
print "input is not valid"
self.clues()
def sorting(self):
#if self.fixwords == 0:
#self.fixwords = (words_open.read())
#else:
#pass
self.symbol = raw_input("what symbol would you like to replace? >>> ")
if self.symbol in self.fixwords:
self.nletter = raw_input("that symbol is valid, what letter would you like to swap it with >>> ")
self.nletter.upper()
#self.fixwords.replace(self.symbol, self.letter[, max])
#self.fixwords.replace(self.symbol, self.nletter)
string.replace(self.fixwords, self.symbol, self.nletter.upper)
print self.fixwords
print self.cluesclues
self.prechange()
elif self.symbol not in self.fixwords:
print "That symbol is not valid or has already been changed"
self.sorting()
def prechange(self):
self.change = raw_input("Do you want to change a letter for another letter? yes or no >>> ")
self.change = self.change
if self.change == "yes":
self.changing()
elif self.change == "no":
self.sorting()
else:
print "that is not a valid input"
self.prechange()
def changing(self):
self.chanlet = raw_input("what letter would you like to replace? >>> ")
if self.chanlet in self.fixwords:
self.letchan = raw_input("that letter is valid, what letter would you like to swap it with >>> ")
self.fixwords = string.replace(self.fixwords, self.chanlet, self.letchan)
print self.fixwords
self.sorting()
elif self.chanlet not in self.fixwords:
print "That letter does not exist"
self.changing()
game = Game()
game.menu_display()
you can use replace() function. It can replace any character in a string even if it exists several times. All you have to do is each time a user select a symbol to replace and a letter, you loop on the list of encoded words and replace that symbol with the letter :
symbol = input("Enter the symbol to replace : ")
letter = input("Enter the letter : ")
for i in range(0, len(encoded_list)) :
encoded_list[i] = encoded_list[i].replace(symbol, letter, len(encoded))
import random
words=["cat", "dog", "animal", "something", "whale", "crocodile", "lion", "summer", "boston", "seattle"]
the_word=random.choice(words)
#print(the_word)
a=len(the_word) #number of letter in the word
c=['_'for i in range(a)]#blanks seperated
blanks=" ".join(c)
print("This is a word with",a,"letter")
print("\t", blanks)
guess=0
while guess<3:
answer=input("Please enter a letter: ")
if answer in the_word:
the_index=the_word.index(answer)#find the index
c[the_index]=answer
blanks=" ".join(c)
print(blanks)
else:
guess=guess+1
print("There is no",answer,"in the word.")
I have two problems:
1st I can't reveal 2 words, summer for example, if a user input 'm' it will reveal only the first letter 'm'
2nd when the user input more than one word the program still consider right answer. For example: The user input "nm" for the word "something" the program still consider it right, and the word turn out like this "somethinmg"
You can check the length of answer via something like
if len(answer) != 1:
print "Please enter just one letter"
Or you can simply take only the first letter of what they enter
letter = answer[0]
See How to find all occurrences of an element in a list? on how to find multiple indexes that match.
Okay first of all to do the display I would take the word, split it up into letters and then create a list with the same length containing all '_'. This way you could display the _ _ _ _ etc by calling ' '.join(substitutelist)....
To get multiple letter responses:
each guess call
for letter in range(len(word)):
if word[letter]==guess.lower():
substitutelist[letter]=guess.lower()
Then every time a letter was called I would add it to a list titled something like "USED" and check each guess to make sure its not in zip(word, used) and if it is return a message error.
Here is an example hangman code I wrote to show the different functions...
import re, sys
from random import choice
def showmap(hangmanpic):
"""Will show the hangman pic after subtracting any
characters holding the place of a future body part"""
tempmap=''
x=str(range(7))
for i in hangmanpic:
if i in x:
tempmap+=' '
else:
tempmap+=i
return tempmap
def addbodypart(remaining, hangmanmap):
"""takes the hangman map and substitutes in a body
part when a wrong answer is chosen. Returns the new
hangmanmap"""
bodyparts={'6':'(_)',
'5':'|',
'3':'\\\\',
'2':'\\\\',
'4':'/',
'1':'/'
}
return re.sub(str(remaining), bodyparts[str(remaining)], hangmanmap)
def StartGame(hangmanmap, word):
"""Starts the game"""
dashword, wrong=[], []
remaining=6
for i in word:
dashword.append('_')
while remaining>0:
if '_' not in dashword:
remaining=0
continue
for i in range(5):
print ""
print "Guesses Left = %d" %(remaining)
print showmap(hangmanmap)
print ""
print "Used Letters: %s" %(', '.join(wrong))
print "Word: %s"%(' '.join(dashword))
guess=str(raw_input('Guess a letter:')).lower()
if guess in str(wrong)+str(dashword):
print ""
print "Sorry but you have already guessed that letter. Please guess again."
print ""
continue
if guess not in word:
hangmanmap=addbodypart(remaining, hangmanmap)
remaining-=1
wrong.append(guess)
else:
for i in range(0, len(word)):
if word[i]==guess:
dashword[i]=guess
if '_' not in dashword:
for i in range(5):
print ""
print "You WIN! Congrats"
print "The word was %s" %(word)
print showmap(hangmanmap)
print "Used Letters: %s" %(', '.join(wrong))
print "Word: %s"%(' '.join(dashword))
else:
for i in range(5):
print ""
print showmap(hangmanmap)
print "Word: %s" %(word)
print "Sorry but you've ran out of guesses! You Lose! The correct word was %s" %(word)
def main():
word=str(choice([line.strip() for line in open(sys.argv[1])])).lower()
hangmanmap=""" _________
|/ |
| 6
| 354
| 5
| 1 2
|
___|___"""
print "Welcome to AmazingReds Hangman Game!"
print "6 wrong answers and YOU LOSE! Good Luck."
StartGame(hangmanmap, word)
if __name__ == '__main__':
main()