I am currently coding a text based game for a class I'm taking. I want to have a function with nested functions so I don't have to re-write player options in every single room. Here is what I currently have:
#The loop:
while p_choice != 'quit': #begins room loop
#The Forest Clearing
while room == 'Forest Clearing':
avail_choices = ['north'] + avail_all
room_inv = [] #items in this room
room_desc = ("\nYou are in The Forest Clearing. To the north you see a large cave\n"
"with stone stairs leading down. There doesn\'t seem to be anything\n"
"you can do here...\n")
if p_choice == 'north':
print("\nYou step through the cave entrance and walk cautiously down the
stairs.\n"
"You find yourself in some sort of cavern, filled with an inky darkness. It is
far too\n"
"dark to see much, but nearby, you see a pile of rubbish with a flashlight
sitting on top.")
room = rooms[room][p_choice]
elif p_choice not in avail_choices:
print('You can\'t do that here!')
room = [room]
else:
all_rooms()
#Function I'm trying to call
def all_rooms():
def look():
if p_choice == 'look':
print(room_desc)
room = [room]
I want it to return to the loop after printing the room description. It prints the room description like I want, but then it crashes and I get the following error:
Traceback (most recent call last):
File "C:\Users\jwpru\Desktop\IT140-P1\TextBasedGame.py", line 136, in <module>
all_rooms()
File "C:\Users\jwpru\Desktop\IT140-P1\TextBasedGame.py", line 95, in all_rooms
look()
File "C:\Users\jwpru\Desktop\IT140-P1\TextBasedGame.py", line 72, in look
room = [room]
UnboundLocalError: local variable 'room' referenced before assignment
You are in The Forest Clearing. To the north you see a large cave
with stone stairs leading down. There doesn't seem to be anything
you can do here...
I've also tried:
def all_rooms():
def look():
if p_choice == 'look':
print(room_desc)
global room
and...
def all_rooms():
def look():
global room
if p_choice == 'look':
print(room_desc)
room = [room]
Not sure what to do here. Any help would be appreciated!
Related
This is the code.
#When I try to make the variable ‘enemy’ save globally, it says ‘Variable referenced before assignment.’, or something along those lines. How do I fix this?
#If you are going to suggest to make it all one function, I tried and it didn't work out. I am doing this so I can keep repeating the turn function until the player enters a vaild command.
#Player and enemy stat blocks. Order of stat blocks is: Health, Weapon, Weapon damage, Armor, and Armor type.
PC = [50, 'shortsword', 20, 'chain mail', 10]
goblin = [30, 'dagger', 15, 'leather', 5]
# Function for a single turn.
def turn(enemy):
turn1 = input('Your turn. What would you like to do? ').lower()
if turn1 != 'attack':
print('Invalid command.')
turn(enemy)
elif turn == 'attack':
global enemy
enemy[0] = enemy[0] - PC[2]
# Function for the entirety of combat.
def combat(enemy):
while enemy[0] > 0:
turn1 = input('Your turn. What would you like to do?')
turn(enemy)
combat(goblin)
I have been working on a text-based adventure game. I've revised it a few times and can't seem to get the outcome I want, when I attempt to create EVENTS rather than simply relying on an abundance of PRINT strings. Whenever I choose the option I want (door 1 in this case), then the following options, the input is unresponsive or gives me an error. Below is a portion of the code for door 1. A little clarity would be appreciated!
def main():
import sys
from colorama import init
init()
init(autoreset=True)
from colorama import Fore, Back, Style
def run_event(event):
text, choices = event
text_lines = text.split("\n")
for line in text_lines:
print(Style.BRIGHT + line)
print()
choices = choices.strip()
choices_lines = choices.split("\n")
for num, line in enumerate(choices_lines):
print(Fore.GREEN + Style.BRIGHT + str(num + 1) + ". " + line)
print()
return colored_input()
def colored_input():
return input(Fore.YELLOW + Style.BRIGHT + "> ")
print ("")
print ("")
print (" WELCOME TO THE MAZE ")
print ("")
print ("")
print ("You have found yourself stuck within a dark room, inside this room are 5 doors.. Your only way out..")
print ("")
print ("Do you want to enter door 1,2,3,4, or 5?")
print ("")
EVENT_DOOR1 = ("""
Theres an alien eating what appears to be a human arm, though its so damaged it's hard to be sure. There is a knife next to the alien.
what do you want to do?
""","""
Go for the knife
Attack alien before it notices you
""")
EVENT_ALIEN = ("""
You approach the knife slowly, While the alien is distracted. You finally reach the knife, but as you look up, the alien stares back at you.
You make a move to stab the alien, but he is too quick. With one swift motion, the alien thrusts you into the air.
You land hard, as the alien makes it's way towards you again. What should you do?
""", """
Accept defeat?
Last ditch effort?
""")
EVENT_ALIEN2 = ("""
You catch the alien off-guard. He stumbled and hisses in your direction. You scream in terror before he grabs the knife, and punctures your throat as he rips off your limbs.")
You died.. GAME OVER.. Mistakes can't be made this soon.. OUCH
""")
door = colored_input()
if door == "1":
run_event(EVENT_DOOR1)
alien = colored_input()
if alien == "1":
run_event(EVENT_ALIEN)
elif alien == "2":
run_event(EVENT_ALIEN2)
restart=input("Start over? Yes or No? ").lower()
if restart == "yes":
sys.stderr.write("\x1b[2J\x1b[H")
main()
else:
exit()
main()
You run_event function unnecessarily makes another call to colored_input() when it returns, causing the unresponsiveness as the script waits for another input. Remove the return colored_input() line and your code would work.
Also note that you should add a comma to the single-item tuple assigned to EVENT_ALIEN2; otherwise it would be evaluated as a string:
EVENT_ALIEN2 = ("""
You catch the alien off-guard. He stumbled and hisses in your direction. You scream in terror before he grabs the knife, and punctures your throat as he rips off your limbs.")
You died.. GAME OVER.. Mistakes can't be made this soon.. OUCH
""",)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm trying to create a text-based game. I've made a basic/generic intro and now it's getting long so I want to create a new file so that I can add things like armor and weapons. When I went to try to import 'my_character' it gave me an error so I went to research this problem and I found this, so I tried it. I just got an error message saying it wasn't define (similar to the error below). This is the intro part named intro:
# Date started: 3/13/2018
# Description: text based adventure game
import time
def display_intro():
print('It is the end of a 100 year war between good and evil that had\n' +
'killed more than 80% of the total human population. \n')
time.sleep(3)
print('The man who will soon be your father was a brave adventurer who \n'
+ 'fought for the good and was made famous for his heroism. \n')
time.sleep(3)
print('One day that brave adventurer meet a beautiful woman who he later \n'
+ 'wed and had you. \n')
time.sleep(3)
def main():
display_intro()
main()
gen = input('\nYour mother had a [Boy or Girl]: ')
name = input("\nAnd they named you: ")
print("You are a {} named {}".format(gen, name))
chara_class = None
# Assigning points Main
my_character = {
'name': name,
'gender': gen,
'class': chara_class,
'strength': 0,
'health': 0,
'wisdom': 0,
'dexterity': 0,
'points': 20
}
# This is a sequence establishes base stats.
def start_stat():
print("\nThis is the most important part of the intro")
time.sleep(3)
print("\nThis decides your future stats and potentially future gameplay.")
time.sleep(4)
print("\nYou have 20 points to put in any of the following category: Strength, Health, Wisdom, or Dexterity.\n"
)
def add_character_points(): # This adds player points in the beginnning
attribute = input("\nWhich attribute do you want to assign it to? ")
if attribute in my_character.keys():
amount = int(input("By how much? "))
if (amount > my_character['points']) or (my_character['points'] <= 0):
print("Not enough points!!! ")
else:
my_character[attribute] += amount
my_character['points'] -= amount
else:
print("That attribute doesn't exist! \nYou might have to type it in all lowercase letters!!!")
def remove_character_points():
attribute = input("\nWhich of the catagories do you want to remove from? ")
if attribute in my_character.keys():
amount = int(input("How many points do you want to remove? "))
if amount > my_character[attribute]:
print("\nYou are taking away too many points!")
else:
my_character[attribute] -= amount
my_character['points'] += amount
else:
print(
"That attribute doesn't exist! \nYou might have to type it in all lowercase letters!!!")
def print_character():
for attribute in my_character.keys():
print("{} : {}".format(attribute, my_character[attribute]))
playContinue = "no"
while playContinue == "no":
Continue = input("Are you sure you want to continue?\n")
if Continue == "yes" or "Yes" or "y":
playContinue = "yes"
start_stat()
add_character_points()
elif Continue == "n" or "No" or "no":
main()
running = True
while running:
print("\nYou have {} points left\n".format(my_character['points']))
print("1. Add points\n2. Remove points. \n3. See current attributes. \n4. Exit\n")
choice = input("Choice: ")
if choice == "1":
add_character_points()
elif choice == "2":
remove_character_points()
elif choice == "3":
print_character()
elif choice == "4":
running = False
else:
pass
def story_str():
print(
"\nYou were always a strong child who easily do physical labor and gain lots of muscle."
)
time.sleep(3)
print("\nYou regularly trained with your dad who was also a skilled swordsman.")
time.sleep(3)
print("\nAs you grew into an adult, you're swordsmanship improved drastically.")
time.sleep(3)
print("\nOnce old enough, you joined the local guild as a warrior.")
time.sleep(3)
def story_dex():
print("\nYou were a sly child. You would always be stealing from other people and with"
+ "\nconstant practice you became proficient at thieving.")
time.sleep(3)
print("\nCombined with the skill of knives and short-blades, you became an extremely deadly assassin."
)
time.sleep(3)
print("\nOnce old enough, you joined the local guild as an assassin.")
time.sleep(3)
def story_wis():
print("\nYou grew up as a very intellegent child. You read books everyday and realized that magic"
+ "is the best offensively and defensively.")
print("\nYou grew up and attended the best magic school avalible and graduated."
)
print("\nYou soon went to the local guild and joined as a wizard.")
run_story = False
while run_story:
if my_character['strength'] >= 13:
story_str()
chara_class = 'Warrior'
run_story = True
else:
continue
if my_character['dexterity'] >= 13:
story_dex()
chara_class = 'Assassin'
run_story = True
else:
continue
if my_character["wisdom"] >= 13:
story_wis()
chara_class = 'Mage'
run_story = True
else:
continue
The command I have typed on part1 is to try to import my_character is:
from intro import my_character
print(my_character)
I have been trying to import my_character but it comes up as:
Traceback (most recent call last):
File "C:/Users/user/Desktop/part1.py", line 5, in <module>
my_character
NameError: name 'my_character' is not defined
The original file was named "intro" and the new one is named "part1". Do I need to do the 'if name == "__main"' thing? If so, what does that do?
Check for:
1) is the file name my_character.py
2) you have imported it as my_character
3) my_character is in the main python directory (if you are importing in interpreter)
I'm working on a text based adventure game in python. Nothing super fancy. I want to have a lever in 2 different rooms unlock a gate in a third room. Both levers need to be pulled in order for the gate to be unlocked.
here are the two rooms with the levers.
def SnakeRoom():
choice = raw_input("> ")
elif "snake" in choice:
FirstRoom.SnakeLever = True
print "As you pull the lever... You hear something click down the hall behind you."
SnakeRoom()
elif "back" in choice:
FirstRoom()
else:
dead("Arrows shoot out from the walls. You don't make it.")
def WolfRoom():
choice = raw_input("> ")
elif "wolf" in choice:
FirstRoom.WolfLever = True
print "As you pull the lever... You hear something click down the hall behind you."
WolfRoom()
elif "back" in choice:
FirstRoom()
else:
dead("Arrows shoot out from the walls. You don't make it.")
Here is the room with the gate.
def FirstRoom():
Lever = WolfLever and SnakeLever
choice = raw_input("> ")
if "straight" in choice and Lever != True:
print "You see a large gate in front of you. The gate is locked, there doesn't seem to be any way to open it."
FirstRoom()
elif "straight" in choice and Lever == True:
SecondRoom()
elif "left" in choice:
WolfRoom()
elif "right" in choice:
SnakeRoom()
elif "lever" in choice:
print "WolfLever: %s" % WolfLever
print "SnakeLever: %s" % SnakeLever
print "Lever: %s" % Lever
FirstRoom()
I shortened the code so you don't have to read through all the unnecessary stuff.
My biggest problem is I'm not super familiar with the Python language yet, so I'm not sure how to word everything to find the answers I'm looking for.
edit: Instead of FirstRoom.WolfLever I also tried just using WolfLever, in the body of my code, above Start() I have:
WolfLever
SnakeLever
Lever = WolfLever and SnakeLever
But my functions weren't updating these values. So I tried the FirstRoom. approach.
Credit to #Anthony and the following link: Using global variables in a function other than the one that created them
Globals definitely were the answer (With the exception of using classes). Here's what my WolfRoom() and SnakeRoom() functions look like now:
def WolfRoom():
global WolfLever
choice = raw_input("> ")
elif "wolf" in choice:
WolfLever = True
print "As you pull the lever... You hear something click down the hall behind you."
WolfRoom()
For FirstRoom() I added
global Lever
to the beginning of the function and right before Start() I have
WolfLever = False
SnakeLever = False
this way I have no errors or warnings (Was getting syntax warnings for assigning a value to my levers before declaring them as global) and everything works perfectly.
I am making a game that has you choose from three caves, and each one has a dragon in it. When I run this program, it refuses to run, and says that potatocave is undefined. I am using python 3. I need to know why it will not accept potatocave as defined, what I am doing wrong, and if there is a simpler way of doing this.
EDIT: I ran it again and it says that chosenCave is undefined.
Traceback error says:
Traceback (most recent call last):
File "C:\Python33\Projects\Dragon.py", line 32, in <module>
if chosenCave == str(friendlyCave):
NameError: name 'chosenCave' is not defined
import random
import time
time.sleep (3)
def displayIntro():
print('You are in a land full of dragons. In front of you,')
print('you see three caves. In one cave, the dragon is friendly')
print('and will share his treasure with you. Another dragon')
print('is greedy and hungry, and will eat you on sight.')
print('The last dragon is a Potarian and gives free potatoes.')
def chooseCave():
cave = ''
while cave != '1' and cave != '2' and cave != '3':
print('Which cave will you go into? (1, 2 or 3)')
cave = input()
return cave
def checkCave(chosenCave):
print('You approach the cave...')
time.sleep(2)
print('It is dark and spooky...')
time.sleep(2)
print('A large dragon jumps out in front of you! He opens his jaws and...')
print()
time.sleep(2)
friendlyCave = random.randint(1, 3)
potatocave = random.randint(1, 3)
while potatocave == friendlyCave:
potatocave = random.randint(1, 3)
if chosenCave == str(friendlyCave):
print('Gives you his treasure!')
elif chosenCave == str(potatocave):
print ('Millions of potatoes rain from the sky.')
else:
print('Gobbles you down in one bite!')
playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':
displayIntro()
caveNumber = chooseCave()
checkCave(caveNumber)
print('Do you want to play again? (yes or no)')
playAgain = input()
P.S This was not the final version, I just used a potato cave as a placeholder to figure out the concept of three caves instead of my original two.
Well, the error message says it all: you haven't defined chosenCave by the moment you are trying to compare it to str(friendlyCave), i.e. line 32.
Just imagine you're the interpreter and work through your script from the beginning. Your course of action would be:
import random, import time, sleep for 3 seconds;
as a result, random and time are now recognized names.
define functions displayIntro, chooseCave, checkCave; those are now also known names referring to the respective functions.
assign friendlyCave and potatocave. Reassign the latter in a loop.
compare chosenCave to str(friendlyCave)... wait, what chosenCave?
But, as DSM notes, if lines 28-37 were indented as part of the body of checkCave function, everything would work just fine:
def checkCave(chosenCave):
print('You approach the cave...')
time.sleep(2)
print('It is dark and spooky...')
time.sleep(2)
print('A large dragon jumps out in front of you! He opens his jaws and...')
print()
time.sleep(2)
friendlyCave = random.randint(1, 3)
potatocave = random.randint(1, 3)
while potatocave == friendlyCave:
potatocave = random.randint(1, 3)
if chosenCave == str(friendlyCave):
print('Gives you his treasure!')
elif chosenCave == str(potatocave):
print ('Millions of potatoes rain from the sky.')
else:
print('Gobbles you down in one bite!')