编程学习网 > 编程语言 > 几段 Python 代码理解面向对象
2017
08-10

几段 Python 代码理解面向对象

 

目录

  1. 定义一个游戏输入,对输入简单解析并做出反应
  2. 为游戏对象添加查看状态的方法
  3. 为 Goblin 类添加更详细的信息

 

正文

 

1.定义一个游戏输入,对输入简单解析并做出反应

 

源代码:

a-simple-game.py

# 获取输入并解析出输入对应的动作
def get_input():
    command = input(":").split()
    verbo_word = command[0]
    if verbo_word in verb_dict:
        verb = verb_dict[verbo_word]
    else:
        print("Unknown verb {}".format(verbo_word))
        return

    if len(command) >= 2:
        noun_word = command[1]
        print(verb(noun_word))
    else:
        print(verb("nothing"))

# 具体的动作
def say(noun):
    return "You said {}".format(noun)

# 将动词和动作对应起来
verb_dict = {
    "say": say,
}

while True:
    get_input()

 

运行结果:

 

 

 

2.为游戏对象添加查看状态的方法

代码:

class GameObject:
    class_name = ""
    desc = ""
    objects = {}

    def __init__(self, name):
        self.name = name
        GameObject.objects[self.class_name] = self

    def get_desc(self):
        return self.class_name + "\n" + self.desc


# 创建一个继承自游戏对象类的哥布林类
class Goblin(GameObject):
    class_name = "goblin"
    desc = "A foul creature"

goblin = Goblin("Gobbly")

# 具体的动作
def examine(noun):
    if noun in GameObject.objects:
        return GameObject.objects[noun].get_desc()
    else:
        return "There is no {} here.".format(noun)

 

以上代码创建了一个继承自 GameObject 类的 Goblin 类,也创建一个新的 examine 方法,于是我们添加一个新的 examine 动词进去:

# 将动词和动作对应起来
verb_dict = {
    "say": say,
    "examine": examine,
}

 

代码和上一个小 demo 合并起来,运行看看:

 

 

3.为 Goblin 类添加更详细的信息,并添加 hit 动作,让你可以打 Goblin(有点意思了~)

 

代码(只列出修改过的与添加的):

class Goblin(GameObject):
    def __init__(self, name):
        self.class_name = "goblin"
        self.health = 3
        self._desc = "A foul creature"
        super().__init__(name)

    @property
    def desc(self):
        if self.health >= 3:
            return self._desc
        elif self.health == 2:
            health_line = "It has a wound on its knee."
        elif self.health == 1:
            health_line = "Its left arm has been cut off."
        elif self.health <= 0:
            health_line = "It is dead."
        return self._desc + "\n" + health_line

    @desc.setter
    def desc(self, value):
        self._desc = value

def hit(noun):
    if noun in GameObject.objects:
        thing = GameObject.objects[noun]
        if type(thing) == Goblin:
            thing.health -= 1
            if thing.health <= 0:
                msg = "You killed the goblin!"
            else:
                msg = "You hit the {}".format(thing.class_name)
        else:
            msg = "I'm not strong enough, I can only hit goblin."
    else:
        msg = "There is no {} here.".format(noun)
    return msg

# 将动词和动作对应起来
verb_dict = {
    "say": say,
    "examine": examine,
    "hit": hit,
}

 

运行:

 

这里有 完整代码 ,是不是简单又有趣~点个赞吧~

 

来自:https://zhuanlan.zhihu.com/p/28409354

 

扫码二维码 获取免费视频学习资料

Python编程学习

查 看2022高级编程视频教程免费获取