Making an RPG in Python - 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'"

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

While-Loop Use in Python

When you come to the 2nd while loop while x == 2: it's still repeating the whole script even though x /= 1 (not if "n"is entered). Let say we enter "y" on the prompt "Is this correct?" shouldn't x become 3 which stops both the first and the 2nd loop?
This is probably obvious but I'm pretty new.
# -*- coding: utf-8 -*-
import time
x = 1
while x == 1:
print "What's your name?"
name = raw_input("Name: ")
print "How old are you?"
age = raw_input("Age: ")
print "So you are %r years old and your name is %r. Is this correct?" % (age, name)
correct = raw_input("(y/n): ")
while x == 2:
if correct == "y":
x = 3 # x = 3 skips all whiles, not working
time.sleep(1)
elif correct == "n":
time.sleep(1)
x = 1 # x = 1 --> 1st while still in action
else:
print "Invalid input \n\t Loading..."
x = 2 # x = 2 --> 2nd while takes over
print "Where do you live?"
time.sleep(0.5)
country = raw_input("Country: ")
time.sleep(0.5)
city = raw_input("City: ")
time.sleep(1)
print " \n Data: \n\t Name: %r \n \t Age: %r \n \t Country: %r \n \t
City: %r " % (name, age, country, city )
In the code you never change the value of your x to 2 so your inner loop while x==2: never runs and you loop infinitely. You need to change the value of x just inside the while x==1: loop for you to even enter the second loop.
The while structure is totally unnecessary, use functions instead and chain them
def ask():
print "What's your name?"
name = raw_input("Name: ")
print "How old are you?"
age = raw_input("Age: ")
return decide(name,age) #<-- Goes to decide
def decide(name,age):
print "So you are %r years old and your name is %r. Is this correct?" % (age, name)
correct = raw_input("(y/n): ")
if correct == "y":
return name,age #<-- process finishes
elif correct == "n":
return ask() #<-- goes back to asking
else:
print "Invalid input"
return decide(name,age) #<--Goes back to wait for a valid input
name, age = ask() #<--Starts the whole process
While I like my other answer better, if you want this code to work with just a slight modification, just bring the definition of correct to the inner loop and as Abdul Fatir say, kick in an x = 2. Anyhow using creating a state machine this way is not recommended.
x = 1
while x == 1:
print "What's your name?"
name = raw_input("Name: ")
print "How old are you?"
age = raw_input("Age: ")
x = 2 #<--Necessary
while x == 2:
print "So you are %r years old and your name is %r. Is this correct?" % (age, name)
correct = raw_input("(y/n): ")
if correct == "y":
x = 3 # x = 3 skips all whiles, not working
time.sleep(1)
elif correct == "n":
time.sleep(1)
x = 1 # x = 1 --> 1st while still in action
else:
print "Invalid input \n\t Loading..."
x = 2 # x = 2 --> 2nd while takes over
I like the solution involving chaining functions, but I also think that you could use some help with your input validation. I really nice tool for this is not in to validate it ahead of time. For instance
def ask():
print "What's your name?"
name = raw_input("Name: ")
print "How old are you?"
age = raw_input("Age: ")
return decide(name,age) #<-- Goes to decide
def decide(name,age):
print "So you are %r years old and your name is %r. Is this correct?" % (age, name)
correct = raw_input("(y/n): ")
while correct not in ["y", "n"]:
correct = raw_input("(y/n): ")
if correct == "y":
return (name,age) #<--process finishes
else
return ask() #<-- goes back to asking
Just to be clear, I ripped a large portion of that code from another answer, but I think that doing it that way is more efficient, and puts all acceptable answers in once place for easy viewing. It would even allow for more complex input validation, and potentially let you use a constant or config file to define available options.

Print string instead of error when list is empty

def flips():
print "Alright the workout of the day is a front-flip, back-flip and
side flip"
flips_left = ['side flip', 'front flip', 'back flip']
flip_choice = None
while len(flips_left) > 0:
flip_choice = raw_input("Do a flip ")
if "side flip" in flip_choice:
print flip_lines['side_flip']
flips_left.remove('side flip')
print "Great! Now just do the rest: %s" % flips_left
elif "front flip" in flip_choice:
print flip_lines['front_flip']
flips_left.remove('front flip')
print "Good stuff! This is what you have left: %s" %
flips_left
elif "back flip" in flip_choice:
print flip_lines['back_flip']
flips_left.remove('back flip')
else:
"That is not a type of flip! Try again!"
print "Great! You completed the WOD!"
This question is actually a two-parter:
What I'm doing is telling the user to input 'side flip', 'back flip' or 'front flip'. When they do the input is removed from the list 'flips_left'. That works fine until say the user enters the same flip again, I want to return a message telling them they did that already, and to try again.
For some reason I can't get the program to print the else statement when the user inputs something that isn't 'side flip' 'front flip' or 'back flip'. Any ideas? Thanks!
Your if statement logic isn't checking what remains in flips_left
Your best bet would be to do something more generic such as:
if flip_choice in flips_left:
print flip_lines[flip_choice]
flips_left.remove(flip_choice)
else:
print "Some error"
If you want to keep track of choices already made you could use a dictionary to keep track of which flips have already been performed.
flips_left = {'side flip':True, 'front flip':True, 'back flip':True}
...
if flip_choice in flips_left:
if flips_left[flip_choice]:
print flip_lines[flip_choice]
flips_left[flip_choice] = False
else:
print "You have already done %s!" % flip_choice
else:
print "That is not a valid flip"
Try adding a print keyword before your message:
else:
print "That is not a type of flip! Try again!"

update and save data to a .txt file daily

I'm trying to create something similar to a journal of my daily fluid intake, food, exercise, etc. I have created a few menus do ask user for specific input that is pre-defined in the menus. From there I need to collect all the output print data and save to a file, the file will be updated daily (asking the user for the same pre-defined input.
Code is pretty long, but looks like this:
health = open('healthy.txt','a+')
date = input('Date: ')
#Loop Menu for Exercise info for that day.
loop=True
while (loop):
print ()
print ("----------------------------------")
print ("1 = Yoga")
print ("2 = Cardio")
print ("3 = Walk")
print ("4 = Dance")
print ("5 = Rest/None")
print ("D = Done")
print ("----------------------------------")
print ()
exer = input('Exercise: ')
if (exer =='1'):
print("Yoga")
elif (exer =='2'):
print("Cardio")
elif (exer =='3'):
print ("Walk")
elif (exer =='4'):
print ("Dance")
elif (exer == '5'):
print ("Rest/None")
elif (exer =='d' or exer =='D'):
loop=False
else:
print ("Invalid Option")
#End Exercise Menu
dur = input('Duration(in minutes): ')
#Loop menu for the Food Intake for particular date.
loop=True
while (loop):
print ()
print ("----------------------------------")
print ("1 = Protein")
print ("2 = Starch")
print ("3 = Fruit")
print ("4 = Vegetable")
print ("D = Done")
print ("----------------------------------")
print ()
food = input('Food: ')
if (food =='1'):
print("Protein")
elif (food =='2'):
print("Starch")
elif (food =='3'):
print ("Fruit")
elif (food =='4'):
print ("Vegetable")
elif (food =='d' or food =='D'):
loop=False
else:
print ("Invalid Option")
#End Food Menu
fluid = input('Fluid Intake Total: ')
#for line in health:
#Final print of info to be written to file
#not sure if I need the next four lines
food_true = False
food_total = 0
exer_true = False
exer_total = 0
for char in exer:
if (exer_true == "Yoga"):
print ("Yoga", end=" ")
if (exer_true == "Cardio"):
print ("Cardio", end=" ")
if (exer_true == "Walk"):
print ("Walk", end= " ")
if (exer_true == "Dance"):
print ("Dance",end=" ")
if (exer_true == "Rest/None"):
print ("Rest/None",end=" ")
else:
loop=False
while(loop):
if (food_true == "Protein"):
print ("Protein", end=" ")
if (food_true == "Starch"):
print ("Starch", end=" ")
if (food_true == "Fruit"):
print ("Fruit", end= " ")
if (food_true == "Vegetable"):
print ("Vegetable",end=" ")
else:
loop=False
print ("{:>10}".format("Date: "),date)
print ("{:>10}".format("Exercises: "),exer_total)
print ("{:>10}".format("Duration: "),dur)
print ("{:>10}".format("Foods: "),food_total)
print ("{:>10}".format("Fluids: "),fluid)
print("-"*60)
#Save/Write to file function will be here
#Save/Write to file function will be here
health.write(info)#word "info" is a place holder only for final code info
health.close()
I want to be able to print out the info only (this does not include saving the info to the file)for the following in a neat looking file(format doesn't really matter as long as it is neat): Date: output; Exercise: output(all if applicable) ;Duration:output ;Food:output(all four if applicable);Fluids: output
Each day I will run the program and update my daily info for all the above.
Then the file needs to have the info written and saved to the same file each day(cannot be a new file each day, hence the use of the the following at start of the code, this is a MUST):
health = open('healthy.txt','a+')

This is probably a trivial overlook, just starting out with python

I made a short text adventure for my human phys class about the liver.
link: http://pastebin.com/QYkn5VuU
#SUPER LIVER ADVENTURE 12!
from sys import exit
from random import randint
quips = ["Welcome!",
"have a wonderful day",
"Livers are cool!",
"this text was chosen at random",
"Writen in python",
"woo, splash text!",
"Notch loves ez!",
"Almost dragon free!"]
print quips [randint (0, len(quips) -1)]
def first_thing () :
print "You are a liver, congratulations! You should do some liver stuff now."
print "Here comes some blood, what should you do?"
filterblood = raw_input (">")
if filterblood == "filter" or "filter blood" or "filter the blood":
return 'second_thing'
elif filterblood == "who cares":
print "I care, be more considorate!"
return "first_thing"
else:
print "Sorry, no (Hint, it is your main purpose!)"
return "first_thing"
def second_thing () :
print "You are now filtering the blood, good for you!"
print "oh no! There is too much aldosterone! what would that do?"
fluidz = raw_input (">")
if fluidz == "fluid retension" or "Keeping fluids":
return 'third_thing'
else:
print "nope! (hint, what does aldosterone do?)"
return "second_thing"
def third_thing () :
print "Oh no!, that's bad!"
print "What should you do about that aldosterone?"
metabolize = raw_input (">")
if metabolize == "metabolize" :
return 'fourth_thing'
else:
print "BRZZZZ, wrong!"
return "third_thing"
def fourth_thing () :
print "super duper!"
print "the aldosterone has been taken care of, no problems at the current moment"
print "..."
print "..."
print "..."
print "After a couple of months a problem arises, you are inflamed, what could this be?"
hepatitis = raw_input (">")
if hepatitis == "hepatitis":
return 'fifth_thing'
else:
return "fourth_thing"
def fifth_thing () :
print "OH NO! Hepatitis!"
print "What could have caused this?"
idunno_somthing = raw_input (">")
if idunno_somthing == "infection" or "an infection" :
print "neat, thats no good."
print "thank you for coming"
exit (0)
elif idunno_somthing == "sex" or "drugs" or "rock n roll":
print "very funny, what specificly caused it?"
return "fifth_thing"
else:
return "fifth_thing"
ROOMS = {
'first_thing': first_thing,
'second_thing': second_thing,
'third_thing': third_thing,
'fourth_thing': fourth_thing,
'fifth_thing': fifth_thing
}
def runner(map, start):
next = start
while True:
room = map[next]
print "\n--------"
next = room()
runner(ROOMS, 'first_thing')
#if you steal my stuff, credit me.
I had to type in hepatitis twice (lines 66 and 67)and none of the elif's worked.
edit: What am I missing?
This is probably a really stupid question, I'm just starting out. We were all beginners at once.
Your elif statement on line 82 reads:
elif idunno_something == "sex" or "drugs" or "rock n roll":
this should be
elif idunno_something in ("sex", "drugs", "rock n roll"):
The same sort of change should help on lines 22, 38 and 77.
For fun, I completely fixed up your program.
#!/usr/bin/python
# SUPER LIVER ADVENTURE 12!
# If you steal my stuff, credit me.
# Owen Sanders on StackOverflow
#
# Updated December 5, 2011
# OregonTrail on StackOverflow
from sys import exit
from random import randint
quips = [
"Welcome!",
"have a wonderful day",
"Livers are cool!",
"this text was chosen at random",
"Writen in python",
"woo, splash text!",
"Notch loves ez!",
"Almost dragon free!"
]
print quips[randint(0, len(quips)-1)]
def first_thing():
print ("You are a liver, congratulations! "
"You should do some liver stuff now.")
print "Here comes some blood, what should you do?"
filterblood = raw_input ("> ")
if filterblood in ("filter", "filter blood", "filter the blood"):
return 'second_thing'
elif filterblood == "who cares":
print "I care, be more considorate!"
return "first_thing"
else:
print "Sorry, no (Hint, it is your main purpose!)"
return "first_thing"
def second_thing():
print "You are now filtering the blood, good for you!"
print "oh no! There is too much aldosterone! what would that do?"
fluidz = raw_input ("> ")
if fluidz in ("retain fluid", "fluid retention", "keep fluids",
"keep fluid"):
return 'third_thing'
else:
print "nope! (hint, what does aldosterone do?)"
return "second_thing"
def third_thing():
print "Oh no!, that's bad!"
print "What should you do about that aldosterone?"
metabolize = raw_input ("> ")
if metabolize == "metabolize":
return 'fourth_thing'
else:
print "BRZZZZ, wrong!"
return "third_thing"
def fourth_thing():
print "super duper!"
print ("the aldosterone has been taken care of, no problems at the "
"current moment")
print "..."
print "..."
print "..."
print ("After a couple of months a problem arises, you are inflamed, "
"what could this be?")
hepatitis = raw_input ("> ")
if hepatitis == "hepatitis":
return 'fifth_thing'
else:
return "fourth_thing"
def fifth_thing():
print "OH NO! Hepatitis!"
print "What could have caused this?"
idunno_somthing = raw_input ("> ")
if idunno_somthing in ("infection", "an infection"):
print "neat, thats no good."
print "thank you for coming"
exit (0)
elif idunno_somthing in ("sex", "drugs", "rock n roll"):
print "very funny, what specificly caused it?"
return "fifth_thing"
else:
return "fifth_thing"
ROOMS = {
'first_thing': first_thing,
'second_thing': second_thing,
'third_thing': third_thing,
'fourth_thing': fourth_thing,
'fifth_thing': fifth_thing
}
def runner(rooms, start):
nextRoom = start
while True:
room = rooms[nextRoom]
print "--------"
nextRoom = room()
runner(ROOMS, 'first_thing')
Since you are a beginner, I will start with some suggestions on asking for help. Ideally, you want to provide the smallest amount of code as possible that shows the problem that you are having. Explain what you expect to happen, and what does actually happen when you execute the code that you have presented.
When you want to check if a string is multiple values, you put the possible values in a list or tuple.
if filterblood in ["filter", "filter blood", "filter the blood"]:
In the case of the example above you may want to accept all answers that start with "filter":
if filterblood.startswith("filter"):

Categories

Resources