pygam中全局变量的问题

2024-10-01 11:37:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图为我的暑期游戏项目制作一个体验系统,但由于某些原因,它似乎没有延续到体验系统的功能上。以下是我所做的:

global currentxp
currentxp = 0
global level
level = 1
def exp_system():
    import random
    mobxp = random.randrange(1, 20, 1)
    currentxp = currentxp
    currentxp = currentxp + mobxp
    level = currentxp
    if currentxp >= 100:
        print("You Leveled Up!")
        level_up = True
    if currentxp < 100:
        level_up = False
        print("You need more xp to level up!")
    if level_up:
        currentxp = 0
        print("Your Current XP is now:")
        print(currentxp)
        level = level + 1
        print("You current level is now:")
        print(level)
        improvestst = input("Choose a stat to improve:(Health or Attack Power)")
    else:
        print("Your Current XP is now:")
        print(currentxp)
        print("You current level is now:")
        print(level)

为了测试系统,我使用了以下方法:

mobhealth = 0
if mobhealth >= 0:
    victory = True
if victory:
    exp_system()
    victory = False

然而,我得到UnboundLocalError:在Python控制台上currentxp=currentxp赋值之前引用了局部变量'currentxp'。我希望有人能告诉我我做错了什么,并用我的变量举个例子。谢谢!你知道吗


Tags: youifis系统randomlevelsystemglobal
2条回答

我会去掉全局变量,只是传入并返回变量。你知道吗

import random

currentxp = 0
level = 1


def exp_system(currentxp, level):

    mobxp = random.randrange(1, 20, 1)
    currentxp = currentxp + mobxp

    if currentxp >= 100:
        print("You Leveled Up!")
        level_up = True
    if currentxp < 100:
        level_up = False
        print("You need more xp to level up!")
    if level_up:
        currentxp = 0
        print("Your Current XP is now:")
        print(currentxp)
        level = level + 1
        print("You current level is now:")
        print(level)
        improvestst = input(
            "Choose a stat to improve:(Health or Attack Power)")
    else:
        print("Your Current XP is now:")
        print(currentxp)
        print("You current level is now:")
        print(level)

    return currentxp, level


mobhealth = 0
if mobhealth >= 0:
    victory = True
if victory:
    currentxp, level = exp_system(currentxp, level)
    victory = False

Output:

You need more xp to level up! Your Current XP is now: 17 You

current level is now: 1

你的条件太复杂了。对程序员来说,保持简单是一条很好的规则。你知道吗

if currentxp >= 100:
    print("You Leveled Up!")
    currentxp = 0
    level = level + 1
    improvestst = input("Choose a stat to improve:(Health or Attack Power)")
else:
    print("You need more xp to level up!")
print("Your Current XP is now:")
print(currentxp)
print("You current level is now:")
print(level)

上面的代码用更少的代码做同样的事情(顺序略有不同)。你知道吗

您没有正确使用global关键字,如this section of the Python's Programming FAQ所示,必须在函数中使用global,否则,您的变量将被视为局部变量。你知道吗

快速示例(但不应阻止您检查链接):

currentxp = 0
level = 12

def exp_system():
    global currentxp
    currentxp = 5 # works
    currentxp = level #works
    print(level) #works

    # level = 13 # won't work

exp_system()

另外,将所有导入内容放在文件的顶部也是一个很好的做法。你知道吗

相关问题 更多 >