0

对不起,如果标题令人困惑。如果我使用了错误的术语。我上周才开始编码。

我正在为文本冒险游戏的boss战编写掷骰子函数,虽然我可以让骰子函数在函数外使用原始全局变量,减去一个数字并在函数内报告它,但它没有函数运行后更新全局变量。因此,下次我尝试调用该函数时,它再次使用原始值,这完全违背了最初将骰子放在那里的目的。(你永远不能杀死老板,哈哈)

这是我一直在尝试调试的内容。提前致谢!

player = "Dib"
playerhealth = 3
boss = "Zim"
bosshealth = 5

import random

def dice(who, whohealth):
    min = 1
    max = 3
    dice = random.randint(min, max)

    if dice == 1:
        print "Your opponent lost no health"
        print "Your opponent has %d health" % whohealth
    elif dice == 2:
        print "%s hits" % who
        whohealth = whohealth - 1
        print "Your opponent lost 1 health"
        print "Your opponent has %d health" % whohealth
    elif dice == 3:
        print "%s crits" % who
        whohealth = whohealth - 2
        print "Your opponent lost 2 health"
        print "Your opponent has %d health" % whohealth
    else:
        print "stuff"

dice(player, bosshealth)
dice(player, bosshealth)

dice(boss, playerhealth)
dice(boss, playerhealth)
4

2 回答 2

0

你再也没有whohealth回来;Python 通过引用传递对象,但您在函数中重新绑定引用:

whohealth = whohealth - 1

只为本地名称分配一个新值whohealth;原始参考未更新。

处理这个问题的最好方法是返回新值:

def dice(who, whohealth):
    min = 1
    max = 3
    dice = random.randint(min, max)

    if dice == 1:
        print "Your opponent lost no health"
        print "Your opponent has %d health" % whohealth
    elif dice == 2:
        print "%s hits" % who
        whohealth = whohealth - 1
        print "Your opponent lost 1 health"
        print "Your opponent has %d health" % whohealth
    elif dice == 3:
        print "%s crits" % who
        whohealth = whohealth - 2
        print "Your opponent lost 2 health"
        print "Your opponent has %d health" % whohealth
    else:
        print "stuff"

    return whohealth

bosshealth = dice(player, bosshealth)
bosshealth = dice(player, bosshealth)

playerhealth = dice(boss, playerhealth)
playerhealth = dice(boss, playerhealth)

现在该函数返回新的健康值,您可以将该值分配回bosshealthorplayerhealth全局变量。

于 2013-10-09T17:27:01.827 回答
0

不要尝试重写东西,但这是使用字典的另一种方法。

player = {
  'name' : "Dib",
  'health' : 3
}
boss = {
  'name' : "Zim",
  'health' : 5
}

import random

def attack(attacker, attacked):
    min = 1
    max = 3
    dice = random.randint(min, max)

    if dice == 1:
        print "Your opponent lost no health"
        print "Your opponent has %d health" % attacked['health']
    elif dice == 2:
        print "%s hits" % attacker['name']
        attacked['health'] -= 1
        print "Your opponent lost 1 health"
        print "Your opponent has %d health" % attacked['health']
    elif dice == 3:
        print "%s crits" % attacker['name']
        attacked['health'] -= 2
        print "Your opponent lost 2 health"
        print "Your opponent has %d health" % attacked['health']
    else:
        print "stuff"

attack(player, boss)
attack(player, boss)

attack(boss, player)
attack(boss, player)
于 2013-10-09T17:27:01.893 回答