0

申し分なく、私は高校で約半年の経験を持つまったく新しいプログラマーです(Pythonで)。基本的なテキスト ゲームを作成していて、何時間も費やしたエラーが発生しましたが、解決できないようです。間違った方法で質問した場合は申し訳ありませんが、これが私の最初の質問です。

これが私のコードです:

############################################################################
#               APOCALYPSE GAME - TEXT EDITION                             #         
#               version 0.0.1                                              #
############################################################################
### BEGINNING TEXT. ###
print('Hello, and welcome to my apocalypse game - text edition!')
print()
print('This is my first game, and I would like to make a graphical version')
print('later in my career.')
print()
print('But, for now, here is the text edition of it so you can get a taste')
print('of what is to come.')
print()
print('NOTE: PLEASE ENTER ALL TEXT IN ALL CAPS.')

print('CHARACTER SETUP:')
print()
def gender(): ### ALLOWS USER TO PICK A GENDER FOR THERE CHARACTER.
    womanOrMan = input('Are you a woman or a man(answer WOMAN/MAN)?')
    if womanOrMan == 'MAN':
        print('You are a man.')
        customizationMan()
    elif womanOrMan == 'WOMAN':
        print('You are a woman.')
        customizationWoman()
    else:
        print('Invalid answer. Please try again.')
        gender()

def customizationMan(): ### CHARACTER CUSTOMIZATION FOR MEN. ###
    print('NOTE: IN THIS AREA YOU MAY USE LOWER CAPS. I WILL TELL YOU WHEN TO USE CAPS AGAIN.')
    hair = input('What hairstyle do you have?')
    hairColor = input('What is the color of your hair?')
    eyeColor = input('What is the color of your eyes?')
    noseSize = input('How big is your nose(inches)?')
    beard = input('What is the name of your beard(if none say "NONE")?')
    bodyType = input('What is your body type?')
    race = input('What is your race?')
    clothes = input('What are you wearing?')

    print()
    print('Here is a summary of you: ')
    print()
    print('You have a ' + hair + ' hairstyle, and you the color of it is ' + hairColor + '.')
    print('Your eyes are the color ' + eyeColor + '.')
    print('Your nose is ' + noseSize + ' inches long.')
    if beard == 'NONE':
        print('You are clean shaven.')
    else:
        print('You have a ' + beard + ' beard.')
    print('You have a ' + bodyType + ' body type.')
    print('You are of ' + race + ' background.')
    print('You are wearing ' + clothes + '.')
    characterConfirmation()


def customizationWoman():### CHARACTER CUSTOMIZATION FOR WOMEN.###
    print('NOTE: IN THIS AREA YOU MAY USE LOWER CAPS. I WILL TELL YOU WHEN TO USE CAPS AGAIN.')
    hair = input('What hairstyle do you have?')
    hairColor = input('What is the color of your hair?')
    eyeColor = input('What is the color of your eyes?')
    noseSize = input('How big is your nose(inches)?')
    bodyType = input('What is your body type?')
    race = input('What is your race?')
    clothes = input('What are you wearing?')

    print()
    print('Here is a summary of you: ')
    print()
    print('You have a ' + hair + ' hairstyle, and you the color of it is ' + hairColor + '.')
    print('Your eyes are the color ' + eyeColor + '.')
    print('Your nose is ' + noseSize + ' inches long.')
    print('You have a ' + bodyType + ' body type.')
    print('You are of ' + race + ' background.')
    print('You are wearing ' + clothes + '.')
    characterConfirmation()

def characterConfirmation(): ### CONFIRMS USER WANTS HIS CHARACTER TO LOOK LIKE HIS SELECTIONS FOR SURE. ###
    print('BEGIN TO ANSWER IN ALL CAPS ONCE AGAIN.')
    print('Are you sure this is what you want your character to look like(if you')
    print('enter "YES" you will move on. If you enter "NO" the character creation')
    print('process will restart)?')
    characterRestart = input('Enter "YES" or "NO" now:')
    if characterRestart == "YES":
        attributeSelection()
    elif characterRestart == "NO":
        print('Restarting character creation.')
        gender()
    else:
        print('Invalid answer. Please try again.')
        print()
        print()
        characterConfirmation()


gender()




#####################################################################################################################################
#####################################################################################################################################
#                                                           CHARACTER ATRRIBUTES                                                    #
#####################################################################################################################################
#####################################################################################################################################


def attributeSelection():
    print("Ok. Now it is time to set your character attributes and then you can begin the game")
    print()
    print("You're character attributes are very important. They can determine whether or not")
    print("you survive a certain situation.")
    print("YOU HAVE 25 SKILL POINTS. SPEND THESE ON THE FOUR ATTRIBUTES")
    print("STRENGTH, VITALITY, STEALTH, AND EXPERIENCE.")
    print()
    print()
    print("Strength makes you able to kill enemies faster, and to do tasks that")
    print("you normally coulden't.")
    print()
    print("Vitality makes you able to survive longer in combat situations.")
    print()
    print("Stealth makes you more likely to beable to avoid cobat situations when they are not")
    print("necessary and sneak up on enemies when they are.")
    print()
    print("Experience makes you more likely to be able to survive bad weather conditions,")
    print(" enhances your ability to preserve food, and helps you survive on your own")
    print(" in the wild in general.")
    print()
    print()
    print("TIME TO SELECT YOUR ATTRIBUTES:")
    print()

    balance = 25
    print("Your SP balance is currently 25.")
    strength = input("How much SP do you want to put into strength?")
    balanceAfterStrength = balance - strength
    if balanceAfterStrength == 0:
        print("Your SP balance is now 0.")
        attributeConfirmation()
    elif strength < 0:
        print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
        attributeSelection()
    elif strength > balance:
        print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
        attributeSelection()
    elif balanceAfterStrength > 0 and balanceAfterStrength < 26:
        print("Ok. You're balance is now at " + balanceAfterStrength + " skill points.")
    else:
        print("That is an invalid input. Restarting attribute selection.")
        attributeSelection()

    vitality = input("How much SP do you want to put into vitality?(" + balanceAfterStrength + " left!)")
    balanceAfterVitality = balanceAfterStrength - vitality
    if balanceAfterVitality == 0:
        print("You SP balance is now 0.")
        attributeConfirmation()
    elif vitality < 0:
        print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
        attributeSelection()
    elif vitality > balanceAfterStrength:
        print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
        attributeSelection()
    elif balanceAfterVitality > 0 and balanceAfterVitality < 26:
        print("Ok. You're balance is now at " + balanceAfterVitality + " skill points.")
    else:
        print("That is an invalid input. Restarting attribute selection.")
        attributeSelection()

    stealth = input("How much SP do you want to put into stealth?(" + balanceAfterVitality + " left!)")
    balanceAfterStealth = balanceAfterVitality - stealth
    if balanceAfterStealth == 0:
        print("Your SP balance is now 0.")
        attributeConfirmation()
    elif stealth < 0 :
        print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
        attributeSelection()
    elif stealth > balanceAfterVitality:
        print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
        attributeSelection()
    elif balanceAfterStealth > 0 and balanceAfterStealth < 26:
        print("Ok. You're balance is now at " + balanceAfterStealth + " skill points.")
    else:
        print("That is an invalid input. Restarting attribute selection.")
        attributeSelection()

    experience = input("How much SP do you want to put into experience?(" + balanceAfterStealth + " left!")
    balanceAfterExperience = balanceAfterStealth - experience
    if balanceAfterExperience == 0:
        print("Your SP balance is now 0.")
        attributeConfirmation()
    elif experience < 0:
        print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
        attributeSelection()
    elif experience > balanceAfterStealth:
        print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
        attributeSelection()
    elif balanceAfterExperience > 0 and balanceAfterStealth < 26:
        print("Oops! You did not spend all of your skill points. Restarting attribute selection.")
        print(" remember to spend all of them this time!")
        attributeSelection()
    else:
        print("That is an invalid input. Restarting attribute selection.")
        attributeSelection()

def attributeConfirmation():
    print("ATTRIBUTE CONFIRMATION TEST SUCCESS!")

問題は、シェルでコードを実行すると、次のようになることです。

Hello, and welcome to my apocalypse game - text edition!

This is my first game, and I would like to make a graphical version
later in my career.

But, for now, here is the text edition of it so you can get a taste
of what is to come.

NOTE: PLEASE ENTER ALL TEXT IN ALL CAPS.
CHARACTER SETUP:

Are you a woman or a man(answer WOMAN/MAN)?MAN
You are a man.
NOTE: IN THIS AREA YOU MAY USE LOWER CAPS. I WILL TELL YOU WHEN TO USE CAPS AGAIN.
What hairstyle do you have?UGLY MULLET
What is the color of your hair?BROWN
What is the color of your eyes?BLUE
How big is your nose(inches)?5
What is the name of your beard(if none say "NONE")?NONE
What is your body type?ATHLETIC
What is your race?WHITE
What are you wearing?JEANS AND A TSHIRT

Here is a summary of you:

You have a UGLY MULLET hairstyle, and you the color of it is BROWN.
Your eyes are the color BLUE.
Your nose is 5 inches long.
You are clean shaven.
You have a ATHLETIC body type.
You are of WHITE background.
You are wearing JEANS AND A TSHIRT.
BEGIN TO ANSWER IN ALL CAPS ONCE AGAIN.
Are you sure this is what you want your character to look like(if you
enter "YES" you will move on. If you enter "NO" the character creation
process will restart)?
Enter "YES" or "NO" now:YES
Traceback (most recent call last):
    File "C:/Python32/APOCALYPSE GAME LIBRARY/apocalypseGame.py", line 96, in <module>
        gender()
    File "C:/Python32/APOCALYPSE GAME LIBRARY/apocalypseGame.py", line 22, in gender
        customizationMan()
    File "C:/Python32/APOCALYPSE GAME LIBRARY/apocalypseGame.py", line 54, in customizationMan
        characterConfirmation()
    File "C:/Python32/APOCALYPSE GAME LIBRARY/apocalypseGame.py", line 85, in characterConfirmation
        attributeSelection()
NameError: global name 'attributeSelection' is not defined

なぜこのエラーが発生するのかわかりません。関数attributeSelectionを定義していないことを私に伝えていると思いますが、明らかに定義しました。私もすべてのスペルをチェックしました...だから私は困惑しています。これを修正する方法を知っている人はいますか?助けてくれてありがとう。

4

2 に答える 2

3

gender()コードの一番下にある 1 行を右に移動してみてください。

呼び出されたとき、必要なメソッドなどattributeSelectionはまだ定義されていません。

于 2012-11-30T00:46:36.363 に答える
0

jvivenot has already answered the original question, but I wanted to offer a more detailed and generic answer for anyone who might find this post and is experiencing similar issues.

This type of problem caused because Python is not a compiled language, unlike Java or C. In a compiled language, the code is kind of "pre-run"; the computer reads all of your code builds all of your functions before any of your code is actually run. Python does not do this. Python runs each line, in order, one at time, top to bottom. This means that Python cannot look ahead to the bottom of the file. The problem happens when one line of code is attempting to use a function that Python hasn't seen yet because it hasn't read that part of the code yet.

In the code given in the question, gender() is run before attributeSelection() is defined. Python has not seen attributeSelection() yet so, as far as Python knows, it does not exist. Unfortunately, gender() tries to runattributeSelection() but since it doesn't exist, Python raises this nameerror.

There is a simple way to avoid this: Always perform all of your definitions at the top of your program before your main program body. This way you ensure that Python can see and create all of your functions before it begins trying to run your main program. This also help keep your code organized and easy to read.

于 2012-11-30T01:25:32.313 に答える