-1

所以我正在制作一款文字冒险游戏,目前我正在制作敌人。我的班级 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() 的地方。在这也是我定义“p”是什么的地方。

4

1 回答 1

2

因此,首先,遵循命名约定。对于 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.

一些注意事项:除非有长期惯例(例如使用ifor 循环计数器),否则避免使用单字母变量。如果您定义player而不是仅定义p.

Python 为所有这些东西提供了一个非常棒的教程

于 2013-11-16T20:21:07.840 回答