Python:如果else在一个类“init”中,那么这个方法有效吗?

2024-04-19 11:55:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我是另一个正在经历“艰难学习Python”的编程新手,遇到了一些我不完全理解的问题。

在这之前,我会说,虽然我真的很喜欢他的教案,但一个不幸的副作用似乎是,我不太了解编程界的许多技术性话题。我花了两天的时间才弄明白什么是“实例化”,即使现在我也只觉得自己明白了,呵呵。所以我希望我的问题的答案还没有被问到一个更具技术性的描述方式,如果它有我很抱歉是多余的。

无论如何,我在这里要做的是一个完整的文本冒险,使用类来描述每个房间。实际上,我正在做的是将我的一个旧工作导入到这个新的、更“OOP”的工作方式中——转换一个实际上是980行函数调用的程序。

所以之前我在每个功能中都有这些“房间”,它们会检查你是否达到了某些游戏目标,以便向你描述房间。示例:

def room_one():
    if "flashlight" in pack:
        print "You see an exit to the NORTH and a bear to the EAST."
    elif "flashlight" not in pack:
        print "It's too dark to see."

无聊的房间,但恰当的描述。所以在尝试使用类来实现这一点时,我似乎遇到了困难。我将向您展示我用来定义游戏“runner”和room类的代码。

class Runner(object):
    def __init___(self):
        self.goals = [] #an array for game achievements (talked_to_king, etc)
        self.pack = [] #an array for game items (flask, key, etc)

    def play(self, currentroom, gamestate):

        while True:

            print "\n--------"
            print currentroom.desc #this line prints the room description, could
            cmd = raw_input("> ")  #it also be part of the problem?
            gamestate.state = currentroom.actions(cmd)

            if gamestate.state != "SAME":
                currentroom = gamestate.state

            else:
                pass

class Room(object):
    def __init__(self):
        self.desc = "null" #short room description
        self.lookdesc = "super null" #longer room description for the LOOK command


    def actions(self, cmd):
        if 'help' in cmd:
            print """
            'look' -- see your surroundings, including exits.
            'get' -- to pick up an item (if it can be picked up).
            'inventory' -- displays your collected items
            'throw' -- some objects can be thrown
            'talk' -- speak to someone
            Other commands, or objects to interact with, will tend to
            show up IN UPPERCASE. (but still type them in lowercase!)
            Cardinal directions (north, south, east, west) for movement.
            """
            return "SAME"
        elif 'inv' in cmd:
            print "--Inventory--\n"
            for items in game.pack:
                print items
            print "-------------\n"
            return "SAME"
        elif 'look' in cmd:
            print self.lookdesc
            return "SAME"
        elif 'goals' in cmd:
            for goal in game.goals:
                print goal
            return "SAME"
        else:
            print "That won't work here."
            return "SAME"


class Office(Room):

    def __init__(self):

        super(Office, self).__init__()
        # here's the part that doesn't work
        if 'principal' in game.goals:
            self.desc = "You're in the principal's office, and there's a zombie in here!"
        else:
            self.desc = "You're in the principal's office."

        self.lookdesc = "The walls in here are dingy from decades of smoking.\nA door to the WEST leads back to the foyer."



    def actions(self, cmd):

        if "west" in cmd and not "principal" in game.goals:

            print "Buck up and talk to the old prune."

            return "SAME"

        elif "talk" in cmd:

            print "You call to the principal."
            game.goals.append('principal')
            next = raw_input("--Mr. Friiiiinkseseeees...--")
            print "But OH MY DAMN he's actually a zombie now."
            next = raw_input("--Aww weak--")
            return "SAME"

        return super(Office, self).actions(cmd)

为了检查是否追加了“goals”数组,我在Room父类中添加了一个简单的目标检查函数,并且确保追加了game.goals。但我的if-else语句似乎没有实际作用;无论目标数组中有什么,我回到房间时总是得到else'desc。

公平地说,把if-else放在房间里就好像是在黑暗中开枪,事实上我很惊讶没有收到错误信息告诉我那不是他们要去的地方!但它似乎并不关心game.goals数组的内容这一事实告诉我,这并不是最好的方法。我应该如何实现这一点?

作为一个子问题-在这样的程序中,如果游戏状态发生了足够大的变化,以至于一个房间的内容发生了显著的变化,那么对于这个变化的房间来说,有一个完整的其他类被认为更好吗?更重要的是保持“地图”并且说无论游戏状态发生了什么变化,RoomThree(Room)总是RoomThree,或者当游戏回到RoomThree时,这个地方已经被破坏,被洗劫,着火,充满吸血鬼和莴苣的味道,那应该是一个完全不同的RoomThree吗?我希望每个房间都是“那个房间”,让game.goals和game.pack等内容更改类的实例,而不是在满足某些条件时创建一个新类,这样似乎更合理。

不管怎么说,这是冗长的。我是不是做得很奇怪??

再次编辑:清理了主要问题的代码以满足这里人们建议的新代码,还添加了父类“Room”以查看这是否不是问题的一部分。仍然没有解决方案,但是我相信代码的质量已经提高了:)whee

最后编辑(我希望):啊哈,斯通的回答再次非常有帮助。因为我要把“相同的”返回给我的跑步者,所以它使用了Office的旧实例。我需要创建一个全新的实例来让它识别更改;通过返回“Office()”而不是“SAME”,我完成了这项工作。感谢大家不仅帮助解决了手头的问题,而且使代码更易于阅读,并帮助我改变对冗长的if-else语句的想法。Mwah:天


Tags: thetoinselfcmdgameforreturn
2条回答

我想是这样的:

    if not 'principal' in game.goals:

你的意思是:

    if 'principal' not in game.goals:

或者这个:

    if not ('principal' in game.goals):

not 'somestring'False,因为非空字符串总是True,并且您的目标中没有False,所以它的计算结果总是False


在何处创建Office对象?因为您只检查对象创建的条件,并且主体在创建后被添加到目标中,所以如果您再次使用同一对象,描述将不会更改。

如果你有100个房间怎么办?你的游戏功能是否有100个if语句,仅仅是为了设置你所在的房间?(基本上,再设定一次)

当游戏状态改变时,最好直接将其设置为您想要的任何状态。

编辑:我只是重新读了一遍你现在的问题似乎很明显,除非你遗漏了重要的代码。

只有在类Office的成员函数中,您才会将主体添加到目标中。因此,当您开始向目标添加主体时,为时已晚,Office已经初始化,除非您创建新的Office实例,否则不会重新初始化。添加目标后,需要更新文件室的说明。

相关问题 更多 >