幾段 Python 代碼理解面向對象
目錄
- 定義一個游戲輸入,對輸入簡單解析并做出反應
- 為游戲對象添加查看狀態的方法
- 為 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
本文由用戶 david85142 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!