Troubles in text adventure python game - python-3.x

In my computer's class we were tasked with creating a text adventure game in python. I've gotten something down already, but I could only get so far with my knowledge. I'm probably missing something super simple, but I'm just stuck right now.
It's a multiple choice deal where the character is presented with 3 options, look around, move or access inventory. I'm stumped at how to make the code go off on it's own tangent.
I have it to where the player can get a description of their surroundings, but if they do and the options come back up, it sort of bugs out and displays the options again and then the next player input stops the code all together. So if the player "Looks around" and then decides they want to "Move" the code stops.
And, in the first area, there are two directions you can go, north and east. Even if you go East and then look around you get the description of what the Northern room looks like.
Also, I need help getting an inventory system fleshed out. I have no idea how i'd do that.
And there are certain times in the game (at least I planned to have them included) where the player could make statements like "Get insert item here" how would I create those actions?
Here's the code.
import random
import time
print ("You awake in what looks like an adandoned diner with a pounding headache.")
d1a = input ("""What would you like to do?:
1. Look around
2. Move
3. Inventory """)
while d1a != "1" and d1a != "2":
#add option 3 to the loop
d1a = input ("What would you like to do?")
if d1a == "1":
print()
print ("It looks like an old diner. Dust and grime coat the tables, chairs and counter tops. You see a door to the North and another to the East.")
print()
time.sleep(1.5)
d1a = input ("""What would you like to do?:
1. Look around
2. Move
3. Inventory """)
elif d1a == "2":
d2a = input ("""Where?
North
West
South
East""")
while d2a != "North" and d2a != "north" and d2a != "West" and d2a != "west" and d2a != "South" and d2a != "south" and d2a != "East" and d2a != "east":
d2a = input ("Where?")
if d2a == "North" or d2a == "north":
print()
print ("You go through through the door to the North")
print ("which has lead to you what looks to be the kitchen")
print()
time.sleep(1)
elif d2a == "East" or d2a == "east":
print()
print("You step through the door to the east which")
print ("takes you out to the streets. They look")
print ("musty and old, cracks ravaging the asphalt.")
print()
time.sleep(1)
elif d2a == "West" or d2a == "west":
print()
print ("I can't move there.")
print()
time.sleep(1)
elif d2a == "South" or d2a == "south":
print()
print ("I can't move there.")
print()
time.sleep(1)
d1a = input ("""What would you like to do?:
1. Look around
2. Move
3. Inventory """)
while d1a != "1" and d1a != "2":
#add option 3 to the loop
d1a = input ("What would you like to do?")
if d1a == "1":
print()
print ("Must be the kitchen area. You can see stoves, ovens, cabinets containing pots and pans. A dishwasher is open exposing a group of knives. If they're clean or not is unknown.")
print()
time.sleep(1.5)
d1a = input ("""What would you like to do?:
1. Look around
2. Move
3. Inventory """)
elif d1a == "2":
d2a = input ("""Where?:
North
west
south
East""")
Sorry, I'm relatively new to coding, my class just started delving into it but I wanted to test what I could do with this game.

I think that when you move North/east, you should assign a variable, 'location', for example, to the place you move to. then, when you look around, you should use an if statement to see what the location is and then write the correct description.

Related

Python3 How do I make randomized multiple choice questions/answers?

Basically I'm doing a multiple choice question president quiz on who served before the others in said multiple choice question. I've gotten it down fully looped with out the randomness but now I've incorporated arrays and random questions, basically I need to figure out how to make multiple choice questions and then define the logic so that when a person inputs 1,2, or 3 the game will look at all three listed options and know which one is the lowest on the presidents list to identify the correct answer.
lives = True
import array
import random
print("Welcome to Ahmed's U.S Presidential Quiz!")
print("Please enter your name!")
userName = input()
def answer():
if response == presidents
def lifeCount():
if livesRemaining == 0:
print("You're out of lives! Good luck trying again!")
quit()
if livesRemaining == 0:
quit()
while lives:
presidents = ["George Washington","John Adams","Thomas Jefferson","James Maddison","James Monroe","John Quincy Adams",
"Andrew Jackson","Martin Van Buren","William Henry Harrison","James K. Polk","Zachary Taylor","Franklin Pierce","James Buchanan","Abraham Lincoln",
"Ulysses S. Grant","Rutherford B. Hayes","James A. Garfield ","Grover Cleveland","Herbert Hoover","Calvin Coolidge","Franklin D. Roosevelt","Harry S. Truman",
"Dwight D. Eisenhower","John F. Kennedy","Richard Nixon","Jimmy Carter","Ronald Reagan","Bill Clinton","George W. Bush","Lyndon B. Johnson"]
livesRemaining = 3
print("Nice to meet you", userName,)
print("Today you'll be taking a quiz on which U.S President served first out of three options!")
print("You'll have only three chances to mess up! Let's get started!")
print("Choose either number 1 2 or 3 on your keyboard!")
print(random.choice(presidents)); print(random.choice(presidents)); print(random.choice(presidents))
response = input()
if response == "1":
print("Correct! 1/10!")
else:
livesRemaining -= 1
print("Incorrect!")
lifeCount() ```

How to select a single dictionary value from user input key with a loop

Pasting my code below.
I'm trying to create a text based game. In this portion I want my user to make a selection from the given items. If their selection is correct then they move out of the puzzle. If incorrect then they are to be prompted to try again.
I understand a list can be used to do this, but I feel less code can be used using a dictionary,and quality of life much better than:
challenge_1_response = input("> ").lower()
challenge_1_answers = ["magnifying glass", "beaker", "serrated knife", "callendar"]
if challenge_1_response == "magnifying glass":
print("If I look hard enough, I can see...")
elif challenge_1_response == "beaker":
print("If I smash that Beaker I can use the shard to cut loose")
elif challenge_1_response == "serrated knife":
print("You've cut loose")
elif challenge_1_response == "callendar":
print("Oh no. Has it really been that long?")
while challenge_1_response not in challenge_1_answers:
print("I can only choose what's in front of me")
challenge_1_response = input("> ").lower()
if challenge_1_response == "magnifying glass":
print("If I look hard enough, I can see...")
elif challenge_1_response == "beaker":
print("If I smash that Beaker I can use the shard to cut loose")
elif challenge_1_response == "serrated knife":
print("You've cut loose")
elif challenge_1_response == "callendar":
print("Oh no. Has it really been that long?")
Please see that this tidbit segment was just to be used as an example. The idea is that with a dictionary all possible keys along with their follow up message will be in a single variable as opposed to writing several lines of code if the same information was in a list. The other side to this is if I wanted to go back and make additions, or edit information, going back to a dictionary is easier.
I've gotten my code to
import sys
import time
import os
os.system("clear")
def puzzle_1():
challenge_1_scene = "The buckles are strapped tightly, it'll be tough prying myself loose. The lights above me are quite bright, it's painful to keep my eyes open. But...I can see there's a table next to me, and on it: [ Magnifying Glass, Beaker, Serrated Knife, Callendar ] Maybe I can use one of them to get out\n"
for character in challenge_1_scene:
sys.stdout.write(character)
sys.stdout.flush()
time.sleep(0.05)
challenge_1_response = input("> ").lower()
challenge_1_answers = {
"magnifying glass": "If I look hard enough, I can see...",
"beaker": "If I smash that Beaker I can use the shard to cut loose",
"serrated knife": "You've cut loose",
"callendar": "Oh no. Has it really been that long?",
}
if challenge_1_response in challenge_1_answers[challenge_1_response]:
print(challenge_1_answers[challenge_1_response])
while challenge_1_response not in challenge_1_answers[challenge_1_response]
print("I can only choose what's in front of me")
challenge_1_response = input("> ").lower()
if challenge_1_response in challenge_1_answers[challenge_1_response]:
print(challenge_1_answers[challenge_1_response])
puzzle_1()
Can this be done with a dictionary?
challenge_1_response = input("> ").lower()
challenge_1_answers = {
"magnifying glass": "If I look hard enough, I can see...",
"beaker": "If I smash that Beaker I can use the shard to cut loose",
"serrated knife": "You've cut loose",
"callendar": "Oh no. Has it really been that long?",
}
if challenge_1_response in challenge_1_answers:
print(challenge_1_answers[challenge_1_response])
while challenge_1_response not in challenge_1_answers:
print("I can only choose what's in front of me")
challenge_1_response = input("> ").lower()
if challenge_1_response in challenge_1_answers:
print(challenge_1_answers[challenge_1_response])
I've seriously been on this all day. I even looped as to the different attempts I was trying. Long story short, I took out the dictionaries index value and just kept the dictionary itself in the "in" statement. When getting to the print statement I can call the user inputted key for its respective value. During the while loop I need it to look for that same statement, otherwise go for a loop.
I swore I tried this before, but must have been doing something wrong. Anyway this works :)
I understand it needs to be touched up, but I was mostly looking for it to function the way I wanted to. Getting it right is a breeze after that.

JUMBLE WORDS ,I want that if once the word is asked to any player should not repeat

I dont want to reapt the word once aksed with one player
i am creating jumble words game but the proble is the word once used are repeating again and again so what should i do to avoid it
please explain what to do
i tried using del also but it did not worked out ,also i tried all pop but still unable to excute
kindly suggest
import random
def choose():
words=["rainbow","computer","science","mathmatics","player","condition","water","reverse","board","education","sharemarket","mango","magnum","mirchi"]
pick=random.choice(words) #to choose random words we have used random library
return pick
def jumble(word):
jumbled="".join(random.sample(word,len(word))) #join function is used to join words together,also random.sample word
return jumbled #randmoly select the word
def thank(p1name,p2name,points_p1,points_p2):
print(p1name,"your score is :", points_p1)
print(p2name,"your score is :", points_p2)
print("THANKS FOR PLAYING\n Have a nice day!!!!!!!")
def play():
p1name=input("player 1, Please enter your name ")
p2name=input("player 2, Please enter your name ")
points_p1=0
points_p2=0
turn=0
while(1):
#computer will give question to players picked words
picked_word=choose()
#now create the question
Q=jumble(picked_word)
print(Q)
#PLAYER 1
if turn%2==0:
print(p1name,"your turn. ")
answer=input("What's in your mind\n")
if answer==picked_word:
points_p1=points_p1+1
print("your score is :" , points_p1)
else:
print("better luck next time", picked_word)
c=int(input("press 1 to continue and 0 to quit"))
if c==0:
thank(p1name,p2name,points_p1,points_p2)
break
#player 2
else:
print(p2name,"your turn. ")
answer=input("What's in your mind\n")
if answer==picked_word:
points_p2=points_p2+1
print("your score is :" , points_p2)
else:
print("better luck next time", picked_word)
c=int(input("press 1 to continue and 0 to quiet "))
if c==0:
thank(p1name,p2name,points_p1,points_p2)
break
turn=turn+1
play()
To not repeat words add below code. It will maintain a list of already chosen words so far and if it's already used then it will again go to choose till it gets unused word.
def play():
p1name = input("player 1, Please enter your name ")
p2name = input("player 2, Please enter your name ")
points_p1 = 0
points_p2 = 0
turn = 0
chosen_words = []
while (1):
# computer will give question to players picked words
while (1):
picked_word = choose()
if picked_word in chosen_words:
pass
else:
chosen_words.append(picked_word)
break
# now create the question
Q = jumble(picked_word)
print(Q)
word not repeated once asked to any player
Output:
Connected to pydev debugger (build 193.6494.30)
player 1, Please enter your name Pooja
player 2, Please enter your name Meera
rchimi
Pooja your turn.
What's in your mind
mirchi
your score is : 1
ecnscie
Meera your turn.
What's in your mind
science
your score is : 1
ayeprl
Pooja your turn.
What's in your mind
player
your score is : 2
stcithmmaa
Meera your turn.
What's in your mind
mathmatics
your score is : 2
mharreeakts
Pooja your turn.
What's in your mind
sharemarket
your score is : 3
waret
Meera your turn.
What's in your mind
water
your score is : 3
noiitcdno
Pooja your turn.
What's in your mind
condition
your score is : 4
ndiueocta
Meera your turn.
What's in your mind
education
your score is : 4
gammun
Pooja your turn.
What's in your mind
magnum
your score is : 5
uertocpm
Meera your turn.
What's in your mind
computer
your score is : 5
servere
Pooja your turn.
What's in your mind
reverse
your score is : 6
nogma
Meera your turn.
What's in your mind
mango
your score is : 6
iraownb
Pooja your turn.
What's in your mind
rainbow
your score is : 7
abdor
Meera your turn.
What's in your mind
board
your score is : 7

.upper Command not Working

I am currently making a text based rpg, and to solve the problem of case sensitivity during inputs, I used .upper to make it all uppercase. However, it seems to not work in my code. Can someone please help?
if weapon in normalswords or weapon in fireswords or weapon in airswords or weapon in grassSwords:
if weapon in normalswords:
print (normalswords[weapon])
while y== True:
variable= input("Equip? Yes or No")
variable.upper()
if variable== "YES":
print (weapon, "Equipped")
x= False
y=False
elif variable == "NO":
x= True
else:
print ("That is not a valid answer")
y=True
str.upper() returns a copy of the string converted to upper case. It does not modify the string inplace because strings are immutable in Python.
Try this:
variable = variable.upper()

how do you break code in a if loop?

okay two questions my instructor wants me to break my code after my else statement because the menu() function keeps repeating itself after "customer not found" but I don't understand what she means also for some reason my code only runs using only the first name in the "customers" list instead of all the names if anybody could point out the flaws in my code that would be great thank you.
#Program 3 BankApp
def customerind(customer):
ind = ""
for i in range(len(customers)):
if customer == customers[i]:
ind = i
if ind != "":
return ind
else:
print("customer not found")
def printbalance(index):
print("your remaining balance is", balances[index])
def menu():
print("type D to deposit money", customer)
print("type W to withdraw money", customer)
print("type B to display balance", customer)
print("type C to change user", customer)
print("type E to exit", customer)
def withdraw(index, withdrawAmt):
if withdrawAmt < balances[index]:
balances[index] = balances[index] - withdrawAmt
else:
print("you went over your balance")
def deposit(index, depositAmt):
balances[index] = balances[index] + depositAmt
global customers
customers= ["Mike", "Jane", "Steve"]
global balances
balances= [300, 300, 300]
global index
customer= input("what is your name?")
index= customerind(customer)
printbalance(index)
answer= ""
while answer != "E":
menu()
answer= input("what is your menu choice?")
if answer=="C":
customer= input("who are you?")
index= customerind(customer)
if answer== "W":
withdrawAmt = float(input("how much did you want to withdraw today?"))
withdraw(index, withdrawAmt)
printbalance(index)
if answer=="B":
printbalance(index)
if answer=="D":
depositAmt = float(input("how much did you want to deposit today?"))
deposit(index, depositAmt)
printbalance(index)
You have a few issues here.
1. "for some reason my code only runs using only the first name in the "customers" list"
In your customerind function, you are printing "customer not found" after only the first iteration. You need to move the else statement outside of the for loop so that it can iterate through all of the names.
def customerind(customer):
#Iterate through each name, and see if there is a match.
for i in range(len(customers)):
if customer == customers[i]:
return i #If we found the name, instantly return the index.
#Outside of the for loop, will get called once above finishes iterating through all names.
return -1 #Return -1 if no match, since the index can be any value 0 -> Infinity
So the way this function works now, is that if the name is found in the for loop, then it returns the index. If the name is not found after iterating through all of the names, then the function will return -1.
Now that this function is setup a bit better, let's look at your main code at the bottom...
menu() is constantly being called so long as the user does not type E. So then if you want to automatically exit if the customer is not found, you should do something like this:
answer= ""
while answer != "E":
menu()
answer= input("what is your menu choice?")
if answer=="C":
customer= input("who are you?")
index= customerind(customer)
if index == -1:
print('Customer not found. Exiting...')
break #Break out of the while loop above so the program exits.
if answer== "W":
withdrawAmt = float(input("how much did you want to withdraw today?"))
withdraw(index, withdrawAmt)
printbalance(index)
if answer=="B":
printbalance(index)
if answer=="D":
depositAmt = float(input("how much did you want to deposit today?"))
deposit(index, depositAmt)
printbalance(index)

Resources