Im making an animation studio/viewer with python - python

Okay, so im making an animation thing where you like can wiew built-in animations or make your own, and this is the code so far:
import time
def bi2():
print """\ \ \ """
time.sleep(.5)
print """ \ \ \ """
time.sleep(.5)
print """ \ \ \ """
time.sleep(.5)
print """ \ \/ """
time.sleep(.5)
print """ \/\ """
time.sleep(.5)
print """ /\/ """
time.sleep(.5)
print """ / /\ """
time.sleep(.5)
print """ / / / """
time.sleep(.5)
print """ / / / """
time.sleep(.5)
proceed1234 = raw_input("| | |")
if proceed1234 == "q":
main_menu()
elif proceed1234 == "b":
animations1()
else:
time.sleep(.5)
bi2()
def play2():#2nd built in
print "Type in 'q' at any time possible to return to the main menu, or 'b' to go to the animations menu."
bi2()
def bi1():
print " | "
time.sleep(.5)
print " |"
time.sleep(.5)
print """ /\"""
time.sleep(.5)
print ''' / \'''
time.sleep(.5)
print " | OO |"
time.sleep(.5)
print ''' \ /'''
time.sleep(.5)
print ''' \/'''
time.sleep(.5)
print " |"
proceed123 = raw_input(" |")
if proceed123 == "q":
main_menu()
elif proceed123 == "b":
animations1()
else:
time.sleep(.5)
bi1()
def play1(): #first built in animation
print "Type in 'q' at any time possible to return to the main menu, or 'b' to go to the animations menu."
bi1()
def animations1(): #pre made animations
print "You are now viewing the pre-made animations."
time.sleep(1)
print "During each animation, hold down enter for the animation to play, or type 'q' then enter to quit."
time.sleep(1)
animation_choice = raw_input("Type in '1' for animation 1, '2' for animation 2, or 'q' to go back to the main menu.: ")
if animation_choice1 == "1":
play1()
elif animation_choice1 == "2":
play2()
elif animation_choice1 == "q":
main_menu()
else:
print "Invalid choice, check spelling and try again."
animations1()
def main_menu():
print "Type in 'q' to quit the program."
print "Type in 'v1' to choose between 2 pre-made animations."
print "Type in 'as' to go to the animation studio."
print "Type in 'v2' to view your custom animations."
choice = raw_input("Or type in 'b' to go back to the explaination of this program.: ")
if choice == "b":
explaination()
elif choice == v1:
animations1() #animations1 is the pre-made one
elif choice == "as":
animation_studio()
elif choice == "v2":
animations2() #animations2 is the custom user-made animations
elif choice == "q":
quitcheck = raw_input("Are you sure you would like to exit the program? (type 'y' or 'n'): ")
if quitcheck == "y":
print "Goodbye."
time.sleep(2)
elif quitcheck == "n":
main_menu()
else:
print "Invalid choice (check spelling/case), returning to main menu ..."
time.sleep(1)
main_menu()
else:
print "Invalid choice, please check your spelling and try again."
main_menu()
def explaination():
print "Welcome to the animation viewer/maker!"
time.sleep(1)
print "In the main menu, you can select what you would like to do."
time.sleep(1)
print "This program uses text characters to animate something in a loop."
time.sleep(1)
print "As long as you don't close this program, it can save 2 different custom animations, and you can view the ones you created or the pre-made ones."
time.sleep(1)
print "With custom animations, you can type anything you want to create animations that loop (see the pre-made ones for ideas/examples). They can be up to 10 lines."
time.sleep(1)
jafsdlk = raw_input("Please press enter to continue.: ")
main_menu()
explaination()
i may have copied the code wrong but i dont know.
anyway, iu havent added the animation studio yet or the ability to make and save custom animations, and its a pretty simple type of program.
but when i put this in notepad and save it as a .py file and run it to test it, i start getting an error when it runs explaination(), it says it has an error with triple quoted strings, but if i make the triple quoted strings with one quote, it gives me EOL while scanning literal, someone help

The backslash \ is an escape character. You typically use it so Python will take the next character literally.
You can prefix the string with r to indicate a raw string or surround it with triple quotes, as you've done. However, you're running into problems with the \ escaping the first " in the close triple-quote of your line, which makes three quotes to open it, and only two to close--which makes it seek out the next ", in the next line, which throws off everything else.
Right:
print r"This works because there's a space after the slash \ "
Wrong:
print r"This doesn't \"
https://docs.python.org/2.7/reference/lexical_analysis.html#string-literals

Related

Why is PyCharm giving error in input() and print() functions - 'Unresolved Reference'?

All of my other files (leaving a sopecific) in the project are without error.
Its as shown, only 'Magic-I' is having a problem with print() and input()
I shall give you the whole code:
outcome = {
"hi": "Hello",
"hello": "Hi",
"what's your name": "Magic-I !",
"this": "'this' what?",
"you are mad": "You too.....LEL !!!",
"your hobby": "Solving problems",
"fuck off": ".........",
"i like you": "Me too",
}
help = '''
'calculate' - addition ; subtraction ; multiplication ; division.
'car game' - simple car simulator.
'guess game' - launch a simple guessing game.
'rbi' - launch RBI.
'bye' - exit AI
||type 'help' whenever you need to know these commands||
*It also chat*
'''
print("----------------------------------------------------------------------------------------------------------")
print("\nThis is an AI - 'MAGIC I' !")
print("It chats and complete several other tasks !")
print("\nSome key features (type these to access them): ")
print(help)
k = ""
while True:
res = input("\n> ").lower()
if res in outcome:
k = outcome.get(res)+" !"
print(k)
elif "name" in res:
print("Magic-I !")
elif "fuck" in res:
print('........')
elif "parent" in res:
print("Rakshit")
elif "master" in res:
print("Rakshit")
elif "coder" in res:
print("Rakshit")
elif "programmer" in res:
print("Rakshit")
elif "calc" in res:
import calculator
calculator.calculator()
elif 'car' in res:
import CarGame
elif 'guess' in res:
import GuessGame
elif 'rbi' in res:
import RBI
elif 'ac' in res:
print("Turn it on !!!")
elif 'help' in res:
print(help)
elif res == "bye":
print("Bye..!")
break
elif res == "":
print("You haven't typed anything..!")
else:
print("No.!")
this is the code......if you want something else i can give you...please help !!!
Folder:
Hey, when I tried to fix the print() problem it was showing install print() package, something like that...when I clickd it, I got an error:
maybe you should remove the pythonpath variable in your ~/.bash_profile
you can do that by using:-
#export PYTHONPATH=/usr/local/lib/python2.7/site-packages/
I found the solution by changing the text quotations in my input and print, instead of :
variable = input("Some Text")
Try this :
variable = input('Some Text')
It worked well with single quotes in my code

Python: Mad Libs

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

Making an RPG in Python

The code gets stuck within the yes_or_no function right after the user input. No error message, please help! As you can see all I am trying to do is effectuate a simple purchase, I haven't been able to test the buy_something function, and I'm aware that it may have issues.
#!/usr/bin/env python
import time
# Intro
print "Input Name:"
time.sleep(1)
name = raw_input()
print "Welcome to Tittyland brave %s'" %(name)
time.sleep(2)
print "You are given nothing but 500 gold to start you journey..."
time.sleep(2)
print "Good luck..."
time.sleep(3)
print "Shopkeeper: 'Eh there stranger! Looks like you'll need some gear before going into the wild! Check out my store!'"
time.sleep(4)
print ""
#Inventory and first shop
inventory = {
'pocket' : [],
'backpack' : [],
'gold' : 500,
}
shop = {
'dagger' : 50,
'leather armor' : 150,
'broadsword' : 200,
'health potion' : 75,
}
#Buying items
for key in shop:
print key
print "price: %s" % shop[key]
print ""
print "Shopkeeper: So, you interested in anything?"
answer1 = raw_input()
item = raw_input()
def buying_something(x):
for i in shop:
if shop[i] == x:
inventory[gold] -= shop[i]
inventory[backpack].append(shop[i])
def yes_or_no(x):
if x == 'yes':
print "Shopkeeper: 'Great! So what is your desire stranger"
buying_something(item)
else:
print "Shopkeeper: 'Another time then'"
yes_or_no(answer1)
I fixed both your functions. You had your raw_inputs at the wrong place:
def yes_or_no(purchase_q):
if purchase_q == "yes":
while True:
things = raw_input("Great. What is your hearts desire(type no more to exit shop): ")
if things != "no more":
buying_something(things)
else:
print "Good luck on your journey then"
break
def buying_something(item):
if item in shop.keys():
print "You have %s gold available" %(inventory.get('gold'))
print "Item Added {0}: ".format(item)
backpack_items = inventory.get('backpack')
backpack_items.append(item)
item_cost = shop.get(item)
print "Cost of Item is %s gold coins " %(item_cost)
inventory['gold'] = shop.get(item) - item_cost
What happens is that after this line:
print "Shopkeeper: So, you interested in anything?"
you wait for raw input with this answer1 = raw_input()
Then immediately after you type yes or no, you wait for input again item = raw_input()
Tt's not getting stuck or anything, it's just doing as it's told.
print "Shopkeeper: So, you interested in anything?"
answer1 = raw_input()
item = raw_input() // <-- This is in the wrong place
yes_or_no(answer1)
What you've written requires the user to type in the item they want after the yes or no answer, and regardless of a yes or no. I suggest you move the item = raw_input() into your yes_or_no function.
def yes_or_no(x):
if x == 'yes':
print "Shopkeeper: 'Great! So what is your desire stranger"
item = raw_input()
buying_something(item)
else:
print "Shopkeeper: 'Another time then'"

Python console menu using a dictionary

I'm building a Windows application using Python 2.7 that requires a simple console menu, ex:
Do something
Do something else
Exit
There will be several menus, the main menu will link to others. So I am attempting to avoid the scenario of having a bunch of stacks of if input == "1" code. Similar to this StackOverflow link. My below code is currently skipping the main menu and executing every option in my second menu. I've looked it over but I'm failing to see the logic in why it is performing the way it does.
computer = ""
# need a class for each of the options in power_menu
class power:
def logoff(self, computer):
print "logging off " + computer
def restart(self, computer):
print "restarting " + computer
def shutdown(self, computer):
print "shutting down " + computer
def set_computer():
global computer
#os.system("cls")
# optionally print the banner
computer = raw_input("Computer: ")
# check the computer is online
# move to the main menu with the computer parameter
menu().menu_main(computer)
def func_quit():
sys.exit()
def invalid(computer):
#os.system("cls")
print "INVALID CHOICE!"
menu().menu_main(computer)
class menu():
def menu_main(self, computer):
opts_main = {"1":("Power Options", self.menu_power(computer)),
"2":("Service Options", self.menu_service(computer)),
"3":("Service Tag & Warranty", self.menu_warranty(computer)),
"4":("User Options", self.menu_user(computer)),
"5":("Change Computer", set_computer),
"6":("Quit hd-con", func_quit)
}
for key in sorted(opts_main.keys()):
print "\t" + key + ": " + opts_main[key][0]
ans = raw_input("Selection: ")
try:
opts_main.get(ans, [None, invalid])[1]()
except Exception, e:
print e
#men_sel()
def menu_power(self, computer):
opts_power = {"1":("Logoff", power().logoff(computer)),
"2":("Restart", power().restart(computer)),
"3":("Shutdown", power().shutdown(computer)),
"4":("Main Menu", menu.menu_main),
"5":("Quit hd-con", func_quit)
}
for key2 in sorted(opts_power.keys()):
print "\t" + key2+": " + opts_power[key2][0]
ans2 = raw_input("Selection: ")
try:
opts_power.get(ans2)[1]()
#pow_sel()
except:
raise
My output for the above is looking like this.
Computer: asdf
logging off asdf
restarting asdf
shutting down asdf
1: Logoff
2: Restart
3: Shutdown
4: Main Menu
5: Quit
Selection:
I'm looking for guidance on using a dictionary for use in a console menu, fixes for the existing code, or a recommended direction to take this instead of what i'm looking at.
Thanks in advance.
Your assignment to the dictionary:
opts_main = {"1":("Power Options", self.menu_power(computer)), ...}
is calling menu_power, and storing the return value (None) in the tuple. You can use e.g. functools.partial to avoid this:
from functools import partial
opts_main = {"1":("Power Options", partial(self.menu_power, computer)), ...}

Importing function in python

I am trying to create menu where user can choose which part of the program he/she wants to run. When I am importing function computer automatically runs it rather to wait for user input. What shall I do to run function only when called? My code:
import hangman
menu = raw_input("""Welcome to Menu, please choose from the following options:
1. Hangman game
2.
3.
4. Exit
""")
if menu == 1:
hangman()
elif menu == 2:
"Something"
elif menu == 3:
"Something"
elif menu == 4:
print "Goodbye"
else:
print "Sorry, invalid input"
The code for hangman.py looks like that:
import random
words = ["monitor", "mouse", "cpu", "keyboard", "printer",]
attempts = [] # Stores user input
randomWord = random.choice(words) # Computer randomly chooses the word
noChar = len(randomWord) # Reads number of characters in the word
print randomWord , noChar
print "Hello, Welcome to the game of Hangman. You have to guess the given word. The first word has", noChar, " letters."
def game():
guess = raw_input ("Please choose letter")
attempts.append(guess) # Adds user input to the list
print (attempts)
if guess in randomWord:
print "You have guessed the letter"
else:
print "Please try again"
while True:
game()
chance = raw_input ("Have a guess")
if chance == randomWord:
print "Congratulations, you have won!"
break
Without seeing hangman.py, I would assume that it directly contains the code for running the hangman game, not wrapped in a function. If that's the case, you created a module, no function (yet).
Wrap that code in
def run_hangman():
# Your existing code, indented by 4 spaces
# ...
import it like this:
from hangman import run_hangman
and finally call the function like this:
run_hangman()
So here is the start menu:
import hangman
option = raw_input('1) Start Normal\n2) Quick Start\n3) Default') # '\n' is a new line
if option == '1':
hangman.main()
elif option == '2':
hangman.run_hangman('SKIP')
elif option == '3':
handman.run_hangman('Default User')
Inside your hangman code you want to have it modulated. You should have somthing like this:
def main():
stuff = raw_input('Starting new game. Please enter stuff to do things')
run_hangman(stuff)
def run_hangman(options):
if options == 'SKIP':
important_values = 5
vales_set_by_user = 'Player 1'
else:
values_set_by_user = options
rest_of_code()

Categories

Resources