python - 如何用 Python 制作一个改变游戏当前区域的引擎?

标签 python python-2.7

我目前正在使用《Learn Python The Hard Way》一书来学习 Python。在练习 43 中,我被要求创建自己的游戏,并且我必须遵循以下规则:

  • 我必须使用多个文件。
  • 我必须为我的角色可以到达的每个区域使用一个类。

在我的游戏中,我有不同的区域,它们被表示为类,我需要一个引擎来运行它们。引擎应该设置起始区域,并在我的角色输入正确的命令时更改区域。我不明白如何创建一个引擎,我在网上看到过一些,但我永远无法理解它们是如何工作的。我花了几个小时试图为自己制作一个,但我就是做不到。

这是不同区域的代码: 区域.py:

# Jungle area's are numbered like a keypad on a phone.
from engine import *

class Jungle8(object):
    print "\nYou are south of the jungle.\n"
class Jungle1(object):
    print "\nYou are northwest of the jungle.\n"
class Jungle2(object):
    print "\nYou are north of the jungle."
    print "The Monkey Elder is waiting for you.\n"
class Jungle3(object):
    print "\nYou are northeast of the jungle.\n"
class Jungle4(object):
    print "\nYou are west of the jungle.\n"
class Jungle5(object):
    print "\nYou are in the center of the jungle.\n"
class Jungle6(object):
    print "\nYou are east of the jungle."
    print "You can see a cave with a locked door.\n"
class Jungle7(object):
    print "\nYou are southwest of the jungle.\n"
class Jungle9(object):
    print "\nYou are southeast of the jungle.\n"

这是引擎的代码,基本上是空的:

from areas import *

class Engine(object):

    def __init__(self):
        # No idea on what to do at this point.

有没有办法运行一个类?如果我使用房间的函数,我就能够做到这一点,但是类让我很困惑。

最佳答案

是的,你可以。当类具有 __call__ 时,它是可调用的(函数)方法。

class Jungle6():
    def __call__(self):
        print "\nYou are east of the jungle."
        print "You can see a cave with a locked door.\n"

举个例子。

然后您只需调用该实例即可:

j = Jungle6()
j()

关于python - 如何用 Python 制作一个改变游戏当前区域的引擎?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32034933/

相关文章:

Python 列合并

python - 如何使用 Python 删除元素节点但将其子节点保留在 XML 文件中?

python - 如何在 Python 中对局部变量进行单元测试

Python 将文本写入 .tar.gz

python - 用Sympy、python2.7求解方程组

linux - google-cloud-sdk 安装在 CentOS/usr/local/bin 中找不到正确的 Python 2.7 版本

python - 创建Scrapy永无休止的蜘蛛

javascript - 如何正确处理页面刷新?

python - 为什么我收到 ModuleNotFoundError,当它安装在 sys.path 上时?

python - 使用 matplotlib 在 Python 中绘制直方图