Python:如何使变量 = 1 并且它在不同的 def block 中仍然如此? (对于游戏)

标签 python function python-3.x global

我有一个问题。即使在不同的 def 函数中,你如何让变量保持定义?我有一个函数,目的是查看用户想要多少个 AI,例如,如果他们选择“一个”作为他们想要的 AI 数量,AI1 将等于 1。这里是定义 AI1 的地方:

def AISection():#Same as line 1
    global AI1, AI2, AI3
    print("How many AIs do you want to play with?\nChoices:\n1. One\n2. Two\n3. Three")
    #Asks user next question.
    while(True):
    #Same as line 4.
        UserInput = input("Answer goes here:")
        #same as line 6
        if(UserInput in ['ONE', 'One', 'one']):
        #Same as line 8
            AI1 = 1
            #Only AI1 will be activated.
            break
            #Same as line 

因此,如果他们选择“一”,则只有 AI1 会等于 1。然后一旦发生这种情况,用户将能够选择他们想要多少张卡片。这是基于他们想要激活多少个 AI 因此,在上一段中将选择 One,因此他们可以在下面的代码中从 3 个不同的卡金额中进行选择:

def CardsSection():#Same as line 1
    global AI1, AI2, AI3#Makes sure the AIs are equal to something
    print("How many cards do you want in your hand?")
    #Asks the user for an amount of cards the users wants.
    if(AI1 == 1) and (AI2 == 2):
    #If they choose 2 AIs.
        print("Choices:\n1. Four\n2. Six\n3. Eight")
        #This is so an even amount of cards will be distributed from the deck.
    elif(AI1 == 1) or (AI1 == 1) and (AI3 == 3):
    #If they choose 1 AI or 3 AIs.
        print("Choices:\n1. Five\n2. Seven\n3. Nine")
        #Same is line 68.

但是当我运行代码时,它到达了 def CardsSection(AISection 之后定义 AI1 的部分)。然后给了我一个错误:

Traceback (most recent call last):
  File "python", line 81, in <module>
  File "python", line 68, in CardsSection
NameError: name 'AI1' is not defined

问题是我定义了 AI1 = 1 但我的代码无法识别它。我认为这是因为它是在不同的定义中定义的。我想如果我使用全局“模块”,无论我在什么 def 函数中,无论我将 AI1、AI2 和 AI3 设置为等于它们都会是这样。我怎样才能做到无论我在哪里设置 AI1、AI2、和 AI3 等于(在本例中为 AISection),无论我在哪里,它们都会那样?这是我到目前为止的完整代码:

def StartSection():#The starting section.
    print("Do you want to play?\nChoices:\n1. Yes\n2. No")
    #Asks the user a question.
    while(True):
        #Loops if user doesn't answer properly. 
        UserInput = input("Answer goes here:")
        #Prompts the users.
        if(UserInput in ['YES', 'Yes', 'yes']): 
        #If user says yes.
            print("Great! Now choose your 'AI Settings'.")
            #Praises the user & tells user about next prompt.
            break
            #Stops the loop. Continues to next prompt.
        elif(UserInput in ['NO', 'No', 'no']): 
            #Else, if User says no.
            print("Bye bye!")
            #Farewells to the user.
            quit() 
            #Ends Code.
        else:
        #Else user types neither 'Yes' or 'No'.
            print("That is not a choice! Please try again.")
            #Tells user to choose again.
            print("Here are the choices:\n1. Yes\n2. No")
            #Tells user their choices again; goes back to start.
StartSection()#Ends the section of code.
def AISection():#Same as line 1
    global AI1, AI2, AI3
    print("How many AIs do you want to play with?\nChoices:\n1. One\n2. Two\n3. Three")
    #Asks user next question.
    while(True):
    #Same as line 4.
        UserInput = input("Answer goes here:")
        #same as line 6
        if(UserInput in ['ONE', 'One', 'one']):
        #Same as line 8
            AI1 = 1
            #Only AI1 will be activated.
            break
            #Same as line 12
        elif(UserInput in ['TWO', 'Two', 'two']):
        #Same as line 14
            AI1 = 1
            AI2 = 2
            #AI1 and AI2 are activated. AI3 is not activated.
            break
            #Same as line 12
        elif(UserInput in ['THREE', 'Three', 'three']):
        #Same as line 14
            AI1 = 1
            AI2 = 2
            AI3 = 3
            #All 3 AIs are activated.
            break
            #Same as line 12
        else:
            print("That is not a choice! Pleasse try again.")
            #Same as line 22
            print("Here are your choices:\n1. One\n2. Two\n3. Three")
            #Same as line 24
    print("You selested %s AIs" % (UserInput[0].upper()+UserInput[1::1].lower()))
    #Tells the user that what they select while keeping it in a upper-lower case fashion.
AISection()#Same as line 26
def CardsSection():#Same as line 1
    global AI1, AI2, AI3#Makes sure the AIs are equal to something
    print("How many cards do you want in your hand?")
    #Asks the user for an amount of cards the users wants.
    if(AI1 == 1) and (AI2 == 2):
    #If they choose 2 AIs.
        print("Choices:\n1. Four\n2. Six\n3. Eight")
        #This is so an even amount of cards will be distributed from the deck.
    elif(AI1 == 1) or (AI1 == 1) and (AI3 == 3):
    #If they choose 1 AI or 3 AIs.
        print("Choices:\n1. Five\n2. Seven\n3. Nine")
        #Same is line 68.
    else:
        print("Something didn't go right!")
        #If they happened to choose neither 1, 2, or 3 AIs.
        return StartSection()
        #Returns them basck to start.
CardsSection()

希望对您有所帮助:)。

最佳答案

我相信你正面临一个 scope问题是,尽管您将其定义为全局的,但您并没有在函数之外定义它。如果您在任何函数之外定义这三个变量,那么您的程序似乎可以运行:

def AISection():
    global AI1, AI2, AI3
    AI1 = 0
    AI2 = 0
    AI3 = 0
    print("How many AIs do you want to play with?\nChoices:\n1. One\n2. Two\n3. Three")
    while True:
        UserInput = input("Answer goes here:")
        if UserInput.lower() == "one":
            AI1 += 1
            break

def CardsSection():
    global AI1, AI2, AI3
    print("How many cards do you want in your hand?")
    if AI1 == 1 and AI2 == 2:
        print("Choices:\n1. Four\n2. Six\n3. Eight")
    elif AI1 == 1 or AI1 == 1 and AI3 == 3:
          print("Choices:\n1. Five\n2. Seven\n3. Nine")

另请注意,虽然这不是代码审查,但我强烈建议使用 UserInput.lower() == "one"而不是列表检查,这样会更有效率并接受更多答案("oNe"用于例如,如果用户曾经想输入那个)。

关于Python:如何使变量 = 1 并且它在不同的 def block 中仍然如此? (对于游戏),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37515863/

相关文章:

c - 为什么 pushl %ebp 和 movl %esp, %ebp 在每个 ASM 函数的开头?

python - Anaconda:如何彻底删除 Python 3.4?

python - if-else 理解字典在 python3 中不起作用

django - Python点击项目, "Django is not available on the PYTHONPATH "错误

python - 多索引 - 获取每个第一个索引的第二个索引的最大值

python - python中的循环缩进

javascript - 访问 javascript 中的内部函数

c - 如何从函数中的变量获取值并在 C 中的另一个函数中使用它?

python - 如何使用 python 为拼字游戏创建基于文本的棋盘?

Python 管理存储库 Pycharm