文本冒险,全局和局部变量的问题

问题描述 投票:2回答:1
from random import randint
from time import sleep

pminatk = 0
pmaxatk = 4
playerhp = 15

def atk(minatk, maxatk):
    return randint(minatk, maxatk)

def playerAtk(monsterhp):
    dmg = atk(pminatk, pmaxatk)
    monsterhp -= dmg
    print ("Du gjorde %i skade. Monsteret har nå %i liv igjen" % (dmg, monsterhp))
    sleep(1)
    return monsterhp

def monsterAtk(mminatk, mmaxatk):
    global playerhp
    dmg = atk(mminatk, mmaxatk)
    playerhp -= dmg
    print ("Monsteret gjorde %i skade. Du har nå %i liv igjen" % (dmg, playerhp))
    sleep(1)

def fight(monsterhp, mminatk, mmaxatk):
    global playerhp
    while monsterhp > 0 and playerhp > 0:
        playerAtk(monsterhp)
        if monsterhp > 0:
            monsterAtk(mminatk, mmaxatk)
    if playerhp > 0:
        print ("Gratulerer! Du beseiret monsteret!")
    else:
        print ("Du døde!")

fight(5, 1, 2)
fight(6, 0, 2)

这应该是基于文本的冒险中的简单战斗系统。现在我的问题是,在执行playerAtk后,monsterhp总会回到原来的valye。如果我选择将monsterhp作为全局变量,它将在fight()完成后保持为0,同时使所有其他怪物的hp等于零。现在我可以有多个变量为不同的怪物分配不同的hp值,但有什么方法可以使用参数到fight()函数吗?

python python-2.7 global-variables local-variables
1个回答
0
投票

当你调用while时,你的问题就在你的playerAtk()循环中,你从它返回monsterhp,但实际上并没有在那个循环中使用它,这就是为什么你看到怪物的健康点恢复到原始值。第28行需要阅读:

monsterhp = playerAtk(monsterhp)

代替:

playerAtk(monsterhp)

正如在评论中建议的那样,值得研究定义自定义类。我根据您的代码将以下示例放在一起以激发您的胃口:

from random import randint
from time import sleep

PLAYERNAME = "Player1"
PLAYERHP = 15
PMINATK = 0
PMAXATK = 4


class CharacterDied(Exception):
    def __init__(self, msg):
        self.msg = msg


class Character:
    def __init__(self, name, initial_hp, minatk, maxatk):
        self.name = name
        self.hp = initial_hp
        self.minatk = minatk
        self.maxatk = maxatk

    def take_damage(self, damage_hp):
        self.hp -= damage_hp
        msg = "{} takes {:d}HP damage and has {:d} left."
        print(msg.format(self.name, damage_hp, self.hp))
        if self.hp < 0:
            msg = "{} died."
            raise CharacterDied(msg.format(self.name))

    def attack(self, other):
        dmg = randint(self.minatk, self.maxatk)
        sleep(1)
        other.take_damage(dmg)


def fight(char1, char2):
    try:
        while True:
            char1.attack(char2)
            char2.attack(char1)
    except CharacterDied as death_exception:
        print(death_exception.msg)


if __name__ == "__main__":
    player = Character(PLAYERNAME, PLAYERHP, PMINATK, PMAXATK)
    fight(player, Character("Monster1", 5, 1, 2))
    if player.hp > 0:
        fight(player, Character("Monster2", 6, 0, 2))

有很多方法可以做到这一点。为简单起见,我只编写了一个我们可以用于玩家和怪物的通用Character类,但即使我们开始使用子类定制它们,例如现在战斗更加通用,我们也可以对玩家进行怪物攻击因为它刚刚成为两个战斗角色的功能。

对于你原来的问题,虽然这里寻求的好处是属性是保持和持久的实例对象,这通常比尝试处理和跟踪全局变量更容易遵循。

© www.soinside.com 2019 - 2024. All rights reserved.