首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >试图理解使用对象和类的简单python游戏的流程和逻辑。

试图理解使用对象和类的简单python游戏的流程和逻辑。
EN

Stack Overflow用户
提问于 2013-12-31 00:22:37
回答 2查看 1.1K关注 0票数 2

我正在努力学习Python的艰难之路教程。我回去做了几次练习,想让我真正了解Zed's (作者) OOP示例游戏(练习43)。

小心点,我想我明白了--什么是类和对象。从理论上讲,我至少理解了鱼和鲑鱼、汽车和本田等的区别。

我知道我们使用类和对象(而不仅仅是按需编写函数)来重用代码(对吗?)

我的思维链现在是微妙的,但我不能休息,睡觉或感到满足,直到我得到真正的点击。

游戏有很多场景(场景是游戏中的一个类)。例如,中央走廊,大桥,逃生舱。

除了场景之外,游戏还使用了引擎和Map (对象)。我不完全理解这些组件如何使游戏运行。

在脚本的末尾,开始游戏的代码块是:

代码语言:javascript
复制
a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play() 

具体问题:

  1. 游戏是如何从一个场景移到另一个场景的?
  2. 引擎和地图类是如何在游戏中工作的?也就是说,引擎和地图是干什么用的?我不能完全按照逻辑办事。理想情况下,这可以用一个例子来解释,比如代码中从TheBridge到EscapePod的步骤(游戏流中的最后两个场景)。
  3. 我的说法正确吗:“我理解我们使用类和对象(而不仅仅是按需编写函数)来重用代码。”

游戏如下:

代码语言:javascript
复制
from sys import exit
from random import randint

class Scene(object):
    def enter(self):
        print "This scene is not yet configured. Subclass it and implement enter()."

class Engine(object):

    def __init__(self, scene_map):
        print "Engine __init__ has scene_map", scene_map
        self.scene_map = scene_map

    def play(self):
        current_scene = self.scene_map.opening_scene()
        print "Play's first scene", current_scene

        while True:
            print "\n--------"
            next_scene_name = current_scene.enter()
            print "next scene", next_scene_name
            current_scene = self.scene_map.next_scene(next_scene_name)
            print "map returns new scene", current_scene

class Death(Scene):

    quips = [
        "You died. You kinda suck at this.",
        "Your mom would be proud... if she were smarter",
        "Such a luser",
        "I have a small puppy that's better at this."
        ]

    def enter(self):
        print Death.quips[randint(0, len(self.quips)-1)]
        exit(1)

class CentralCorridor(Scene):

    def enter(self):
        print "The Gothons of Planet Percal #25 have invaded your ship and destroyed"
        print "your entire crew.  You are the last surviving member and your last"
        print "mission is to get the neutron destruct bomb from the Weapons Armory,"
        print "put it in the bridge, and blow the ship up after getting into an "
        print "escape pod."
        print "\n"
        print "You're running down the central corridor to the Weapons Armory when"
        print "a Gothon jumps out, red scaly skin, dark grimy teeth, and evil clown costume"
        print "flowing around his hate filled body.  He's blocking the door to the"
        print "Armory and about to pull a weapon to blast you."

        action = raw_input("> ")

        if action == "shoot!":
            print "Quick on the draw you yank out your blaster and fire it at the Gothon."
            print "His clown costume is flowing and moving around his body, which throws"
            print "off your aim.  Your laser hits his costume but misses him entirely.  This"
            print "completely ruins his brand new costume his mother bought him, which"
            print "makes him fly into an insane rage and blast you repeatedly in the face until"
            print "you are dead.  Then he eats you."
            return 'death'

        elif action == "dodge!":
            print "Like a world class boxer you dodge, weave, slip and slide right"
            print "as the Gothon's blaster cranks a laser past your head."
            print "In the middle of your artful dodge your foot slips and you"
            print "bang your head on the metal wall and pass out."
            print "You wake up shortly after only to die as the Gothon stomps on"
            print "your head and eats you."
            return 'death'

        elif action == "tell a joke":
            print "Lucky for you they made you learn Gothon insults in the academy."
            print "You tell the one Gothon joke you know:"
            print "Lbhe zbgure vf fb sng, jura fur fvgf nebhaq gur ubhfr, fur fvgf nebhaq gur ubhfr."
            print "The Gothon stops, tries not to laugh, then busts out laughing and can't move."
            print "While he's laughing you run up and shoot him square in the head"
            print "putting him down, then jump through the Weapon Armory door."
            return 'laser_weapon_armory'

        else:
            print "DOES NOT COMPUTE!"
            return 'central_corridor'

class LaserWeaponArmory(Scene):

    def enter(self):
        print "You do a dive roll into the Weapon Armory, crouch and scan the room"
        print "for more Gothons that might be hiding.  It's dead quiet, too quiet."
        print "You stand up and run to the far side of the room and find the"
        print "neutron bomb in its container.  There's a keypad lock on the box"
        print "and you need the code to get the bomb out.  If you get the code"
        print "wrong 10 times then the lock closes forever and you can't"
        print "get the bomb.  The code is 3 digits."
        code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
        guess = raw_input("[keypad]> ")
        guesses = 0

        while guess != code and guesses < 10:
            print "BZZZZEDDD!"
            guesses += 1
            guess = raw_input("[keypad]> ")

        if guess == code:
            print "The container clicks open and the seal breaks, letting gas out."
            print "You grab the neutron bomb and run as fast as you can to the"
            print "bridge where you must place it in the right spot."
            return 'the_bridge'
        else:
            print "The lock buzzes one last time and then you hear a sickening"
            print "melting sound as the mechanism is fused together."
            print "You decide to sit there, and finally the Gothons blow up the"
            print "ship from their ship and you die."
            return 'death'

class TheBridge(Scene):

    def enter(self):
        print "You burst onto the Bridge with the netron destruct bomb"
        print "under your arm and surprise 5 Gothons who are trying to"
        print "take control of the ship.  Each of them has an even uglier"
        print "clown costume than the last.  They haven't pulled their"
        print "weapons out yet, as they see the active bomb under your"
        print "arm and don't want to set it off."

        action = raw_input("> ")

        if action == "throw the bomb":
            print "In a panic you throw the bomb at the group of Gothons"
            print "and make a leap for the door.  Right as you drop it a"
            print "Gothon shoots you right in the back killing you."
            print "As you die you see another Gothon frantically try to disarm"
            print "the bomb. You die knowing they will probably blow up when"
            print "it goes off."
            return 'death'

        elif action == "slowly place the bomb":
            print "You point your blaster at the bomb under your arm"
            print "and the Gothons put their hands up and start to sweat."
            print "You inch backward to the door, open it, and then carefully"
            print "place the bomb on the floor, pointing your blaster at it."
            print "You then jump back through the door, punch the close button"
            print "and blast the lock so the Gothons can't get out."
            print "Now that the bomb is placed you run to the escape pod to"
            print "get off this tin can."
            return 'escape_pod'
        else:
            print "DOES NOT COMPUTE!"
            return "the_bridge"

class EscapePod(Scene):

    def enter(self):
        print "You rush through the ship desperately trying to make it to"
        print "the escape pod before the whole ship explodes.  It seems like"
        print "hardly any Gothons are on the ship, so your run is clear of"
        print "interference.  You get to the chamber with the escape pods, and"
        print "now need to pick one to take.  Some of them could be damaged"
        print "but you don't have time to look.  There's 5 pods, which one"
        print "do you take?"

        good_pod = randint(1,5)
        guess = raw_input("[pod #]> ")


        if int(guess) != good_pod:
            print "You jump into pod %s and hit the eject button." % guess
            print "The pod escapes out into the void of space, then"
            print "implodes as the hull ruptures, crushing your body"
            print "into jam jelly."
            return 'death'
        else:
            print "You jump into pod %s and hit the eject button." % guess
            print "The pod easily slides out into space heading to"
            print "the planet below.  As it flies to the planet, you look"
            print "back and see your ship implode then explode like a"
            print "bright star, taking out the Gothon ship at the same"
            print "time.  You won!"

            return 'finished'

class Map(object):

    scenes = {
        'central_corridor': CentralCorridor(),
        'laser_weapon_armory': LaserWeaponArmory(),
        'the_bridge': TheBridge(),
        'escape_pod': EscapePod(),
        'death': Death()
    }

    def __init__(self, start_scene):
        self.start_scene = start_scene
        print "start_scene in __init__", self.start_scene

    def next_scene(self, scene_name):
        print "start_scene in next_scene"
        val = Map.scenes.get(scene_name)
        print "next_scene returns", val
        return val

    def opening_scene(self):
        return self.next_scene(self.start_scene)

a_map = Map('central_corridor')
a_game = Engine(a_map)
a_game.play()
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-12-31 00:56:15

1.游戏如何从一个场景移动到另一个场景?

2.引擎和地图类是如何在游戏中工作的?也就是说,引擎和地图是干什么用的?

也许最好一起回答这两个问题。

Engine通过play()方法设置游戏流程。在该方法中,while循环的每一次迭代,在游戏术语中,您可能都会认为是一个“转”或“圆”。在每一个不同的术语/回合中,以下情况按以下顺序发生:

  • 打印一个仿水平规则;
  • 下一个场景的名称由当前场景的enter()方法确定;
  • 打印一条描述性线条;
  • 将下一个场景的名称指定给scene_map以返回相应的类;
  • 打印了一条描述性行。

while循环的第一行、第三行和第五行只是为了方便您在游戏中看到正在发生的事情。真正的肉在第二和第四行。

游戏是如何从一个场景移到另一个场景的?嗯,Engine类只知道Scene将给它命名,它将查看它的scene_map以查看哪个类与该名称匹配。scene_map基本上是一个字典,它增加了一些功能,可以大喊大叫,嘿,猜猜我现在在做什么,同时它给出了您所识别的类的名称。Engine不需要知道在Scene期间发生了什么,也不需要知道用户如何选择下一个Scene;它所做的就是让您继续重复组成每一轮的五个步骤。

我们如何从一个场景移动到下一个场景取决于我们目前所处的场景。当您编写继承自Scene的类时,您必须定义一个enter()方法,要确保您已经编写了一个功能场景,唯一真正需要做的事情就是确保您的enter()方法在某个时候返回(到Engine)下一个场景的名称。阅读一些场景,当用户提供不同的输入时,您会注意到它们返回不同的场景名称。

当然,如果功能场景没有出现在scene_map中,并且没有其他场景可能返回其名称,从而指示Engine调用其enter()方法,则无法访问功能场景。

我打字很快,因为这是一天的结束,但希望我说了一些事情,你觉得有帮助.祝好运!

票数 4
EN

Stack Overflow用户

发布于 2013-12-31 01:34:24

  1. 游戏的关键部分是这样的代码: 而True: next_scene_name = current_scene.enter() #<-在与用户current_scene = self.scene_map.next_scene(next_scene_name)交互后返回 每个场景的enter方法返回要访问的下一个场景的名称(取决于玩家的操作).这可能又是同一个场景了。然后,next_scene类的Map方法返回匹配该名称的场景实例,并将其赋值给current_scene变量.然后它绕着圈,“进入”新的当前场景。这将无休止地进行下去,或者直到你到达退出程序的Death场景。
  2. 以上基本解释了Engine类。IMHO --它不需要是一个类,只要有一个单独的play函数,就会同样有效(也更简单,因此更好): def play(scene_map):current_scene = scene_map.opening_scene()打印"Play's first S景物“,current_scene current_scene : print”n“ 游戏开始时: a_map = Map('central_corridor') play(a_map) Map类将场景对象实例与场景名称(如'central_corridor')匹配.类的核心是包含实际映射的字典。您可以看到,类的next_scene方法只是对dict键执行一个get。实际上,您可以通过消除Map类来简化代码,只需要一个简单的片段,将琐碎的开始场景逻辑移到Engine类中(或者像我前面提到的play方法)。 但是,对于Map类,我建议通过定义http://en.wikipedia.org/wiki/Application_programming_interface#API_in_object-oriented_languages来实现另一个有用的目的.换句话说,一组与使用游戏地图相关的方法。这意味着,在以后的游戏开发中,如果您意识到您需要一个比dict更复杂的Map逻辑实现,只要您保持API不变(即方法的名称和参数),您就不必更改代码的其余部分。
  3. 类定义了一组行为,并给出了它们的接口。对象是类的实例,它是运行时状态的集合(即类属性的特定值)。 这并不是真正的代码重用。代码重用意味着拥有继承父类行为的子类(而不必复制和粘贴该行为),但是您可以通过使用类获得价值,而无需进行任何子类处理。类就像创建具有共同行为的对象的模板。 在目前的游戏代码中,一些类的使用是毫无意义的。例如Engine类..。您使用一个Map实例初始化它并调用它的play方法,但是由于您只有一个Engine实例,所以没有必要在类中封装该状态( self.scene_map属性)--您可以在调用它时将该状态传递给play方法。 类似地,Scene类及其子类。是的,Scene类定义了一个接口(“场景将有一个enter方法”),但是由于每个场景都不包含任何唯一的状态(即self上的属性),所以不需要有一个实例化的对象,所以只需使用简单的函数就可以更简单地完成相同的任务。 希望其目的是将这些类开发成更有用的结构,从而证明在本教程的未来阶段使用类是合理的。

您可以进一步探讨这些术语的含义:

科学)

科学)

及类似的问题:

很难用ex43的方式学习Python中的类?

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20849812

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档