更新全局列表python

时间:2015-03-21 22:39:47

标签: python list variables global

完全披露 - 这是我的第一个堆栈溢出问题。我在一段时间内搜索了一个类似的问题,但是找不到一个能帮助我学习知识范围有限的问题(有蟒蛇全球变量问题,但答案是我的头脑。)

我是编程的新手,而且我很难通过蟒蛇学习python,这是Zed Shaw的难点。我参加了练习36,我的目标是编写自己的基于文本的游戏。

游戏以以下功能开始

def start():
global Your_HP
Your_HP = 20
global Your_Ammo
Your_Ammo = 20
global HP_Scan
HP_Scan = 2
global your_stats
your_stats = [Your_HP, Your_Ammo, HP_Scan]

print "You enter a room with two doors"
print "Do you choose the Red Door\n...or the Blue door?"
start_choice = raw_input("> ")

if "red" or "Red" in start_choice:
    monster_HP = 2
    monster_attack = 3

    red_one(your_stats, monster_attack, monster_HP)

red_one函数如下所示:

def red_one(your_stats, monster_attack, monster_HP):

    print "Immediately you notice a monster in the room"
    print "You point your rifle at the monster before you"


    shoot(Your_Ammo, monster_HP)

    if monster_HP <= 0:
        print "You killed it!"
        print "You now have %d bullets left" % Your_Ammo
        print "You finally look around the room"
        print "There is a door going straight"
        print "There is a door going left"

        room_choose()


    elif monster_HP > 0:
        print "The monster has %d HP" % monster_HP
        print "He stumbles, but not dead!"
        print "He shoots back at you with his lil pistol!"

        get_shot(monster_attack, Your_HP)

    else:
        dead('just because')

该脚本立即运行拍摄功能,如下所示:

def shoot(Your_Ammo, monster_HP):

    print "---------"
    print "You have %d HP left" % Your_HP
    print "How many shots do you fire?"
    shots_fired = raw_input('> ')
    shots_fired = int(shots_fired)

    Your_Ammo -= shots_fired
    monster_HP -= shots_fired

    return Your_Ammo, monster_HP

问题在于,当我运行脚本并且只拍摄一次时,当我返回red_one的开头时,Your_Ammomonster_HP变量将恢复为原始值我从shoot

返回的更新过的

我尝试移动我宣布全局变量的地方(最初在所有函数之外声明而不是在start中)并且我得到一个&#34; x变量是本地变量全球&#34;错误。

我知道全局变量通常并不总是最好的想法,所以我希望有人能够以优雅的方式为我打破这一点,并提供一个有用的解决方案,无论它是否包含全局变量。

理想情况下,我希望在整个游戏过程中更新your_stats列表中的变量。从本质上讲,从游戏中的任何函数来看,我希望能够返回your_stats列表中的任何变量,这样我就可以将该变量用作其他函数的参数,直到播放器耗尽HP或弹药为止。

对不起,这篇文章有点冗长!任何帮助都非常感谢!

0 个答案:

没有答案