简体   繁体   中英

How would I get my variable to work (Python)?

I've been trying to get a variable working in a game project for school. Pycharm keeps refusing to recognize it as a variable. Is there any mistake in my code? It's been bugging me for a while.

It says:

Shadows name 'gold' from outer scope
Local variable 'gold' value is not used

Code:

import time #Imports a module that creates a pause between events

#Accounts for all responses user might make
option_A = ["A", "a"]
option_B = ["B", "b"]
option_C = ["C", "c"]
yes = ["Y", "y", "yes"]
no = ["N", "n", "no"]
option_gold = ["G", "g", "Gold", "gold"]
option_dagger = ["D", "d", "Dagger", "dagger"]

#Creates object placeholders in user inventory
gold = 0
dagger = 0

#Preventing user from picking a non-existent choice
response = ("\n### Apologies, fellow adventurer. Please use only A, B, or C in your selection. ###\n")

#The story begins with an introduction, and is split into parts
def intro():
  print ("""\nYou suddenly awaken in a dark, menacing forest. Feeling faint and dizzy, you marvel at the tranquility of the forest.  
Suddenly, a grotesque sound pierces the silence, and you turn in fear. A slobbering ogre, brutish and lumbering, starts running towards you. """
  "\n\nWill you: ")
  time.sleep(1)
  print ("""  A. Pick up a large rock and hurl it at the ogre
  B. Lie flat and hope it ignores you
  C. Run for your life""")
  #First choice is made here
  choice = input(">>> ")
  if choice in option_A:
    answer_rock()
  elif choice in option_B:
    print ("\nThat was quick. You seriously think the ogre will ignore you? Oh well. "
    "\n\nYou died! ")
  elif choice in option_C:
    answer_run()
  else:
    print (response)
    intro()

def answer_rock():
  print ("\nThe ogre is momentarily stunned, but quickly regains focus. "
  "\n\nDo you: ")
  time.sleep(1)
  print ("""  A. Get away as fast as you can
  B. Try hurling another rock
  C. Hide in a cave nearby""")
  choice = input(">>> ")
  if choice in option_A:
    answer_run()
  elif choice in option_B:
    print ("""\nYou throw another rock, expecting it to stun the ogre again. 
You missed, badly. The ogre, in a fit of rage, comes after you. """
    "\n\nYou died! ")
  elif choice in option_C:
    answer_cave()
  else:
    print (response)
    answer_rock()

def answer_cave():
  print ("""\nYou hesitate, noting the gloom and ominous darkness inside. 
A glint catches your eye. A dagger juts out of a crevice, wedged in the wall. 
Further into the gloom, you spot a nugget of gold. As the ogre nears, you only have time to grab one. """
  "\n\nDo you grab the dagger, the gold or none at all? - D/G/N ? ")
  choice = input(">>> ")
  if choice in option_dagger:
    dagger = 1
  elif choice in option_gold:
    gold = 1
  else:
    gold = 0
    dagger = 0
  print ("\nAs the ogre nears, what do you do? ")
  time.sleep(1)
  print ("""  A. Silently hide, hoping the ogre has poor night vision
  B. Fight for your life
  C. Sprint towards an abandoned town in the distance""")
  choice = input(">>> ")
  if choice in option_A:
    print ("\nOops! It's fairly obvious ogres can see well in the dark. Too late... "
    "\n\nYou died! ")
  elif choice in option_B:
   if dagger > 0:
    print ("""\nAs you hide in the darkness, the ogre spots a glimmer. Attracted by the shimmering, it reaches over and grabs the dagger. 
Your heart thumps in your chest, and in a moment of bravery, you pierce the ogre's chest with your blade. """
    "\n\nYou survived! ")
   else:
   #If user didn't pick up the dagger
     print ("""\nYou rummage in your belongings. Oh no! You're defenceless. 
Maybe grabbing that dagger would have been a better choice. """
     "\n\nYou died! ")
  elif choice in option_C:
    print ("""You sneak out silently towards the cave exit, but the ogre spots you. 
You make a last, desperate dash towards the light. """)
    answer_town()
  else:
    print (response)
    answer_cave()

def answer_run():
  print ("""\nUsing your great agility, you nimbly outstep the ogre.
However, the ogre puts on a burst of speed and steadily gets closer. You realize running is fruitless. """
  "\n\nWill you: ")
  time.sleep(1)
  print ("""  A. Camoflauge yourself in a leafy shrub
  B. Fight the ogre, knowing you are trapped
  C. Take shelter in a dark cave you spotted earlier""")
  choice = input(">>> ")
  if choice in option_A:
    print ("Your camoflauge proves useless. Ogres aren't that colour-blind! "
    "\n\nYou died!")
  elif choice in option_B:
    print ("\nYou realize an ogre is two tonnes of sheer muscle. You are no match. "
    "\n\nYou died!")
  elif choice in option_C:
    answer_cave()
  else:
    print (response)
    answer_run()

def answer_town():
  print ("""\nPanting and running for your life, you spot a rusted axe submerged in a puddle of mud. 
You attempt to pick it up, but the mud refuses to let go. You continue running, trying to calm down as you shelter behind a crumbling shack. """)
  time.sleep(1)
  print ("The ogre's footsteps echo through the air, and you frantically rummage in your pockets for something you can fight the ogre with.")
  time.sleep(1)
  if gold > 0:
    print ("""\nYou brandish the shiny nugget of gold, meekly hoping it will stop the ogre. 
It pauses and looks at you. Turns out, the ogre was looking for a friend! 
\n\nYou wander the lands with your new best friend, sharing banter and living happily ever after. """
    "\n\nYou survived!")
  else: #If user didn't pick up the gold
     print ("\nYou hold out your empty hands and the ogre snarls, aggravated by this threat. Oops. "
     "\n\nYou died!")

intro()
#Asks if user wants to replay the game
while True:
  print ("\n*** Congratulations. Your bravery has gotten you far. Would you like to play again? - Yes/no?" )
  reply = input(">>> ")
  #Redirects back to introduction
  if reply in yes:
    time.sleep(1)
    print ("\nExcellent choice, brave adventurer. Get ready!" )
    time.sleep(2)
    intro()
  #Farewells user and ends game
  elif reply in no:
    time.sleep(1)
    print ("Farewell, bold adventurer!" )
    break
  else:
    print ("\n### Apologies, fellow adventurer. Please use only Yes or No in your selection. ###\n")

You trying to modify the global variable gold inside a method. To do this you need to use the global statement:

gold = 0
def my_func():
   global gold
   gold = 1

This is not a best practice. Consider using a custom object or a dict to handle the game state.

You are trying to edit the global variable gold in your functions, yet because you have not told the functions to use the global version, when you do gold = 1 , Python defines a new variable for that function with the same name gold , also known as shadowing.

You need to put global gold on the first line of the functions that you want to use that variable.

More info here .

The warning is about the potential danger you are introducing by re-using these names at inner scopes. It can cause you to miss a bug. You should make a better naming, introducing a class, using a global variable, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM