Below is my current code, I have no problems when I enter the go commands but as soon as I try to input the get item name command I get an invalid response. Can someone please help?
# A dictionary for the created text game
# The dictionary links a room to other rooms.
current_room = "Grand Hall"
inventory = []
rooms = {
"Grand Hall": {"South": "Alderaan", "North": "Hoth", "East": "Naboo", "West": "Mustafar"},
"Alderaan": {"North": "Grand Hall", "East": "Tatooine"},
"Tatooine": {"West": "Alderaan"},
"Mustafar": {"East": "Grand Hall"},
"Hoth": {"East": "Kashyyyk", "South": "Grand Hall"},
"Kashyyyk": {"West": "Hoth"},
"Naboo": {"North": "Dagobah", "West": "Grand Hall"},
"Dagobah": {"South": "Naboo"}
}
room_items = {
"Grand Hall": ["Invincibility bracelet"],
"Alderaan": ["Soul Stone"],
"Tatooine": ["Death Stone"],
"Mustafar": ["Chaos Stone"],
"Hoth": ["Genesis Stone"],
"Kashyyyk": ["Evolution Stone"],
"Naboo": ["Nightmare Stone"],
"Dagobah": ["War Stone"]
}
commands = ["go North", "go South", "go East", "go West", "get [item name]", "exit"]
# Define a function to display the available commands
def show_valid_commands():
print("Available commands:")
for cmd in commands:
print("- " + cmd)
# Define a function to display the player's status
def show_status():
print("You are currently in the " + current_room)
print("Inventory: " + str(inventory))
print("Items in this room: " + str(room_items.get(current_room, [])))
# Start the game loop
while True:
# Display the current status and available commands
show_status()
show_valid_commands()
# Get input from the player
command = input("What would you like to do? ")
# Validate the input
if command not in commands:
print("Invalid command. Please enter a valid command.")
continue
# Handle the exit command
if command == "exit":
break
# Handle the get [item name] command
if command.startswith("get "):
item_name = command[4:].strip() # remove leading/trailing whitespaces
if item_name in room_items.get(current_room, []):
room_items[current_room].remove(item_name)
inventory.append(item_name)
print(f"You picked up the {item_name}.")
else:
print(f"There is no {item_name} in this room.")
continue
# Handle the go [direction] command
if command.startswith("go "):
direction = command[3:]
next_room = rooms[current_room].get(direction)
if next_room is None:
print("There's no room in that direction. Please choose another direction.")
else:
current_room = next_room
continue
# Output a message to let the player know the game has ended
print("You have exited the game.")
I'm stuck and I can't wrap my brain around what could be wrong..
I tried out your code and did a bit of debugging on your command test. Basically, this statement works for movement and if one literally entered "get [item name]":
if command not in commands:
What you would want to do is add an addition test for checking that the command starts with "get " something like this:
if command not in commands and command.startswith("get ") == False:
When I tested that refactored code, I could pick up inventory.
Give that a try and see if that meets the spirit of your project.
if command not in commands
Is some kind of optimisation you don't really need.
Drop it and just put at the end of your filters :
print("Invalid command. Please enter a valid command."). continue
Related
So far I have been able to add either one-word values or 2-word values but not both. For example, I want to go to one location and add a skull to my inventory, then move to another location and add an energy potion to my inventory. With my current code, I can add the energy potion by using .split(maxsplit=1) or .split(' ', 1). That was to solve the issue of not being able to add a value with 2 words. But this seems to prevent adding values with one word to the inventory.
while True:
instructions()
player_status(rooms, current_room, inventory)
time.sleep(0.5)
# sets up user command to move player between rooms.
command = input('\nWhat do you want to do?\n>').title().strip()
if command in rooms[current_room]:
current_room = rooms[current_room][command]
time.sleep(0.5)
# command to add item to inventory and remove it from dict.
elif command.lower().split()[0] == 'get':
obj = command.lower().split(maxsplit=1)[1]
if obj in rooms[current_room]['item']:
del rooms[current_room]['item']
inventory.append(obj)
else:
print("I don't see that here.")
# a command to quit the game.
elif command.lower() in ('q', 'quit'):
time.sleep(0.5)
print('\nThanks for playing.')
break
# if player inputs an invalid command.
else:
time.sleep(0.5)
print('\nYou can\'t go that way!')
Here is an example of the output:
You are at occult bookstore.
There is a Skull
You have: ['energy potion']
What do you want to do?
>get skull
I don't see that here.
if obj in rooms[current_room]['item']:
That's searching for skull but Skull doesn't match. You could use [for a case-insensitive search]
if obj.lower() in [i.lower() for i in rooms[current_room]['item']]:
but that doesn't feel very efficient. It might be better to just apply .title() or .capitalize() to obj and make sure that all items in rooms[current_room]['item'] are in consistent format.
racks = "1"
racksPerSecond = 0
gameScreenChoice1 = "Traffic Drugs (1) "
gameScreenChoice2 = "Get Slaves (2) "
print("You are NBA Young Boy (Never Broke Again)")
startScreen = input("To start your journey out the trenches press 1: ")
if startScreen == "1":
print("What do you want to do?")
waysToGetRacks = input(gameScreenChoice1 + gameScreenChoice2)
def TrafficDrugs(slaveQuestion1):
(
slaveQuestion1 == input(" Push P if you want a rack")
if TrafficDrugs(slaveQuestion1):
racks += "1"
)
def getSlaves():
()
if waysToGetRacks == "1":
TrafficDrugs()
if waysToGetRacks == "2":
getSlaves()
Dont ask about the varaibles, but im very confused why im getting a error
You don't need brackets inside your func:
def TrafficDrugs(slaveQuestion1):
slaveQuestion1 == input(" Push P if you want a rack")
if TrafficDrugs(slaveQuestion1):
racks += "1"
you can't call a recursive function you have just defined you need to enter a valid parameter in order to pass the if statement.
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
I am having trouble with my code. When running my code and select the no option to play the game again the game ends. But, I am having trouble with my code when I select the yes option to play again, it does not automatically go back to play the game again. What am I do wrong?
import time
import random
response = []
action_list = ["option1", "option2"]
print(random.choice(action_list))
def print_pause(message_to_print):
print(message_to_print)
time.sleep(2)
def valid_input(prompt, option1, option2):
while True:
response = input(prompt).lower()
if option1 == response:
break
elif option2 == response:
break
else:
print_pause("Sorry, I do not follow.")
return response
def intro():
print_pause("You have approached your apartment building.")
print_pause("You noticed a shadow nearby.")
print_pause("Should you run and drive off to the nearest safe location?")
print_pause("Should you face your fears and attack?")
def adventure_panic():
response = valid_input("Please make your decision. "
"Would you like run or attack?\n",
"run", "attack")
if "run" in response:
print_pause("Run towards your car and drive to a safe location.")
print_pause("Call the police to inform them what you saw.")
elif "attack" in response:
print_pause("Slowly walk towards the nearby shadow.")
print_pause("Grab your pocketknife and pepper spray.")
print_pause("As you come closer to the shadow.")
print_pause("You find out that it is just a cat")
print_pause("Congratulations! You're safe.")
play_again()
def play_again():
response = valid_input("Would you like to play again? "
"Please say 'yes' or 'no'.\n",
"yes", "no")
if "yes" == response:
print_pause("Great, let's play again!")
intro()
adventure_panic()
elif "no" == response:
print_pause("Ok, exit game!")
exit(0)
def play_panic():
intro()
# adventure_panic()
play_panic()
In def play_panic() you only call intro() try to change it to def play_panic(): intro() adventure_panic() play_again()
When I ran your code, I didnt even get to the play again function. Instead of calling the adventure_panic() function in play_panic(), you registered it as a comment with a "#". You also didnt call the play_again function. The actual function works properly for me
import time
import random
response = []
action_list = ["option1", "option2"]
print(random.choice(action_list))
def print_pause(message_to_print):
print(message_to_print)
time.sleep(2)
def valid_input(prompt, option1, option2):
while True:
response = input(prompt).lower()
if option1 == response:
break
elif option2 == response:
break
else:
print_pause("Sorry, I do not follow.")
return response
def intro():
print_pause("You have approached your apartment building.")
print_pause("You noticed a shadow nearby.")
print_pause("Should you run and drive off to the nearest safe location?")
print_pause("Should you face your fears and attack?")
def adventure_panic():
response = valid_input("Please make your decision. "
"Would you like run or attack?\n",
"run", "attack")
if "run" in response:
print_pause("Run towards your car and drive to a safe location.")
print_pause("Call the police to inform them what you saw.")
elif "attack" in response:
print_pause("Slowly walk towards the nearby shadow.")
print_pause("Grab your pocketknife and pepper spray.")
print_pause("As you come closer to the shadow.")
print_pause("You find out that it is just a cat")
print_pause("Congratulations! You're safe.")
play_again()
def play_again():
response = valid_input("Would you like to play again? "
"Please say 'yes' or 'no'.\n",
"yes", "no")
if "yes" == response:
print_pause("Great, let's play again!")
intro()
adventure_panic()
elif "no" == response:
print_pause("Ok, exit game!")
exit(0)
def play_panic():
intro()
adventure_panic() #remove the # so that adventure_panic() is called. If there is a # python registers it as a comment and it is ignored
play_again() #calls the play again function
play_panic()
I'm new in Python but bear with me.
In my code, I am trying to make variable room to 2, via west() function.
Code:
EDIT: I have isolated most of the non-essential code.
room = 1
cmds = 'west'.lower()
def isValidCMD(cmd):
if cmd in cmds:
return True
else:
print("Unknown command. For help type /help, for available options type /options")
cmd = input(">> ")
if isValidCMD(cmd):
runCMD(cmd)
return False
def runCMD(cmd):
if cmd == '/help':
help()
elif cmd == '/exit':
exit()
elif cmd == '/about':
about()
elif cmd == '/stats':
stats()
elif cmd == '/options':
options()
elif cmd == 'north':
north()
elif cmd == 'south':
south()
elif cmd == 'east':
east()
elif cmd == 'west':
west()
elif cmd == '/lookaround':
look_around()
def west():
if room == 1:
print("You head on over to the lab, to get some advice from Professor Andrew.")
return 2 #LINE 40 < -------
elif room == 7:
print("You head back to Auderban Square feeling primed for battle.")
else:
print("You cannot go west.")
cmd = input(">> ")
if isValidCMD(cmd):
runCMD(cmd)
def main():
while True:
# Town
if room == 1:
print("\nYou are at the centre of town, Auderban Square.".upper())
print("\nYou look at the signpost and see 4 signs.")
print("\t- North - Twinleaf Forest")
print("\t- South - Store of Celestia")
print("\t- East - Deskemon Training Ground")
print("\t- West - Auderban's Deskemon centre")
# Lab
elif room == 2:
print("You are at Auderban's Deskemon Centre")
AndrewConv()
print("\nYou see the exit at the door.")
print("\t- East - Auderban Square")
cmd = input(">> ")
if isValidCMD(cmd):
runCMD(cmd)
main()
Output:
But room keeps its value, 1.
Please give some advice for the future so I won't make the same mistake twice.
Replace west() function with this:
def west():
global room
...
Global variables are widely considered bad programming practice because it is extremely difficult to determine where and when they might be modified in a large program. They also make thread-safe and reentrant code almost impossible to write.
A simple approach would be to have each function accept the room as a parameter and return the “new room.” You can then always update the room in your main function every time you invoke a command.
You will probably end up keeping track of more than the room, though. Consider using a mutable data structure like a dictionary or a class to store the game state, and then passing it into your command functions. That way, it is just as simple to keep up with many state variables as one, and you still do not need global variables.
def main():
state = {'room': 1}
while True:
[...]
if isValidCMD(cmd, state):
runCMD(cmd, state)
def west(state):
thisroom = state['room']
if thisroom == 1:
print("You head on over to the lab, to get some advice from Professor Andrew.")
state.update(room=2)
elif thisroom == 7:
print("You head back to Auderban Square feeling primed for battle.")
else:
print("You cannot go west.")
cmd = input(">> ")
if isValidCMD(cmd):
runCMD(cmd)
There are some additional issues with this code. For example, you duplicate the command prompt code in each command prompt, which is brittle and error prone, and unnecessary since you will be returning to main() anyway.
Edited: Here is a minimal, runnable example:
def main():
state = {'room': 1}
for i in range(20):
oldroom = state['room']
nextroom(state)
print("Went from room {} to room {}.".format(oldroom, state['room']))
def nextroom(state):
state['room'] += 2