我的文本冒险游戏Python的另一个名称错误

时间:2013-11-16 20:17:20

标签: python-3.x adventure

所以我正在制作文字冒险游戏,目前我正在制作敌人。我的班级random_enemies为你的角色制作垃圾怪物,我有一个功能,称为弱,正常,强等等......根据你的角色来衡量你的角色。当我调用random_enemies.weak它说(名称错误:全局变量" p"未定义),即使它应该是。

import random
from character import *
from player import *

class random_enemies(character):
    def __init__(self,name,hp,maxhp,attack_damage,ability_power,exp):
        super(random_enemies,self).__init__(name,hp,maxhp)
        self.attack_damage = attack_damage
        self.ability_power = ability_power
        self.exp = exp
    def weak():
        self.hp = random.randint(p.maxhp/10, p.maxhp/5)
        self.attack_damage = None
        self.ability_power = None
        self.exp = None



from character import*
class player(character):
    def __init__(self,name,hp,maxhp,attack_damage,ability_power):
        super(player,self).__init__(name, hp, maxhp)
        self.attack_damage = attack_damage
        self.ability_power = ability_power

这是我的玩家类,下面是玩家获得的等级" maxhp"从

class character(object):
    def __init__(self,name,hp,maxhp):
        self.name = name
        self.hp = hp
        self.maxhp = maxhp
    def attack(self,other):
        pass



p=player(Players_name, 100, 100, 10, 5,)
while (p.hp>0):
    a=input("What do you want to do?")
    if a=="Instructions":
        Instructions()
    elif a=="Commands":
        Commands()
    elif a=="Fight":
        print("Level",wave,"Wave Begins")
        if wave < 6:
            b = random_enemies.weak()
            print("A",b,"Appeared!")
            print("Stats of",b, ": \n Health=", b.hp,"Attack Damage=",b.attack_damage)
            continue

我刚刚快速做到这一点,只是为了测试我所拥有的一切是否正常工作,直到我收到错误。这也是调用random_enemies.weak()的地方。同样在这里我定义了什么&#34; p&#34;是。

1 个答案:

答案 0 :(得分:1)

所以,首先,遵循一个命名约定,对于python代码我建议你使用pep8作为约定。

您的代码中的类与实例存在问题,首先您需要一个类的实例才能使用它:

enemy = random_enemy()  # a better name would be RandomEnemy

在python中,所有方法都以self开头,你需要向方法传递它需要做的工作的参数,weak是一个方法,所以它应该更像这样:

def weak(self, player):
   # the method for weak ... weak attack ?
   # remember to change p to player, which is more meaningful
   ...

现在你有了你的实例并且它有一个接收weak作为参数的方法player,你可以按如下方式使用它:

# you can't use random_enemy here as you tried because it is a class
# you need a random_enemy instance, the enemy that I talked about earlier
b = enemy.weak(player)  # renamed p to player because it is more meaningful

为了使这一切顺利进行,你需要再做一件事,weak()需要返回一些东西。现在你正在使用它返回的东西,没有!您发布的代码为b = random_enemies.weak(),因为weak()没有return条款b始终为None

一些注意事项:避免使用一个字母变量,除非它是一个长期的约定(比如使用i作为循环计数器),如果你调用它player,就更容易理解你想要做什么而不只是p

Python非常棒tutorial for all this stuff