def get_input():
command = input(": ").split()
verb_word =command[0]
if verb_word in verb_dict:
verb = verb_dict[verb_word]
else:
print("Unknown verb {}".format(verb_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)
#描述游戏对象
class Gameobj:
class_name = ""
desc =""
obj = {}
def __init__(self,name):
self.name = name
Gameobj.obj[self.class_name]=self
def get_desc(self):
return self.class_name +"\n"+self.desc
#描述妖精对象的属性
class Goblin(Gameobj):
# class_name = "goblin"
# desc = "A foul creature"
def __init__(self,name):
self.class_name = "goblin"
self.health = 4
#1. 弱的私有方法和属性在开头只有一个下划线。
#这表示它们是私有的,不应该被外部代码所使用。但它只是一个约定,并没有阻止外部代码访问它们。
#它唯一的实际效果是from模块名import*不会导入以单个下划线开头的变量。
#2.强私有方法和属性名称的开始处有一个双下划綫
# Span类的__h方法可以通过: _Span__h 方法外部访问
self._desc ="A foul creature"
super().__init__(name)
#@property属性装饰器
#它们是通过将属性装饰器放在一个方法上面创建的
#这意味着当访问与方法同名的实例属性时,方法将被调用
#属性的一种常见用法是使属性为只读。
@property
def desc(self):
print(self.health)
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
#属性也可以通过定义setter/getter 函数来设置
#setter函数设置相应的属性值
#getter函数获取相应的属性值
#要定义一个setter,你需要使用一个与属性相同名字的装饰器,后面跟着.setter
#这同样适用于定义getter函数
@desc.setter
def desc(self,value):
self._desc = value
#击打函数
def hit(noun):
if noun in Gameobj.obj:
thing = Gameobj.obj[noun]
if type(thing) == Goblin:
thing.health = thing.health - 1
if thing.health <= 0:
msg = "you killed the gonlin!"
else:
msg = "you hit the {}".format(thing.class_name)
else:
msg = "There is no {} here.".format(noun)
return msg
goblin = Goblin("Gobbly")
#检查妖精函数
def examine(noun):
if noun in Gameobj.obj:
return Gameobj.obj[noun].get_desc()
else:
return "There is no {} here.".format(noun)
#函数名集合
verb_dict ={
"say":say,
"examine":examine,
"hit":hit,
}
#使用while循环创建输入窗口
while True:
get_input()
输出:
::::::::: say hello…:说你好
you said “hello” 你说“你好”
::::::::: say goblin…说妖精
you said “goblin” 你说的“妖精”
::::::::: test…测试
Unknown verb test 未知的动词测试
::::::::: examine elf…检查精灵
There is no elf here. 这里没有小精灵。
::::::::: examine goblin…:检查妖精
4
goblin 小妖精
A foul creature 犯规的生物
::::::::: h…h
Unknown verb h 未知的动词h
::::::::: hit goblin… :打妖精
you hit the goblin 你打了小妖精
::::::::: examine goblin…检查妖精
3
goblin 小妖精
A foul creature 犯规的生物
::::::::: hit goblin…:打妖精
you hit the goblin 你打了小妖精
::::::::: examine goblin…:检查妖精
2
goblin 小妖精
A foul creature 犯规的生物
It has a wound on its knee. 它的膝盖上有一个伤口。
:::::::::: hit goblin…:打妖精
you hit the goblin 你打了小妖精
::::::::::: examine goblin…:检查妖精
1
goblin 小妖精
A foul creature 犯规的生物
Its left arm has been cut off! 它的左臂被砍掉了!
::::::::::: hit goblin…:打妖精
you killed the gonlin! 你杀了刚林!
::::::::::: examine goblin…:检查妖精
0
goblin 小妖精
A foul creature 犯规的生物
It is dead. 它已经死了
: