1

我正在使用来自http://www.learnpythonthehardway.org/的优秀教程学习 Python (2.7)

我正在尝试制作一个小型文本输入游戏来提高我的技能,作为其中的一部分,我正在尝试为主角添加一个健康计。我还添加了战斗,这会降低他们的健康。

下面的代码旨在在每场比赛开始时将玩家的健康设置为 100,它通过在名为“Set_Health”的类中执行另一个函数“player_health”来实现

class Health():

    def store_health(self):

        d = Set_Health()
        d.player_health()
        local_health = d.player_health()

        print "Your health is at", local_health, "%"
        return local_health

当执行下面的“punch_received”函数时,玩家的生命值减少 10

class Combat():

    def punch_received(self):

        punch = 10

        x = Health()
        x.store_health()
        combat_health = x.store_health()

        combat_health = combat_health - punch
        print "You have been punched, your health is", combat_health, "%"

到目前为止,一切都很好。它可能不是完美的或最好的方法,但它可以作为学习的基础。

我的问题是我不知道如何将“combat_health”的值返回/发送到另一个变量,例如另一个函数中的“current_hero_health”。

class Hero_Health():

    def current_hero_health(self):

        # I want to store a running total of the heros health in here

非常感谢您对此的任何帮助。谢谢深化

4

2 回答 2

0

您可以向函数添加更多参数。类中定义的函数的第一个参数(与@staticmethodand相对@classmethod)是对象本身,然后函数的所有参数出现:

def current_hero_health(self, value):
    self.health = value

MyHealthObject.current_hero_health(5)
于 2013-05-09T16:27:07.673 回答
0

current_hero_health为你的Hero_Health.

class Hero_Health():

    def __init__(self, current_h):
        self.current_hero_health = current_h

    def current_hero_health(self):
        self.current_hero_health = 3 ; # this is stored total of hero health

您可以从类的任何方法访问成员,使用self.current_hero_health,它存储此类对象的全局计数。

希望这可以帮助。

于 2013-05-09T16:32:08.897 回答