在管理不同的对象及其关系时,面向对象是非常有用的。当你正在开发具有不同特性和功能的游戏时。这一点尤其有用。
让我们看一个示例项目,它展示了类在游戏开发中的用法。这款游戏是一款老式的基于文本的冒险游戏。下面是处理输入和简单解析的函数。
def get_input():
command = input(":").split()
verb_word = command[0]
if verb_word in verb_dict:
verb = verb_dict[verb_word]
else:
print("Unkonwn 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)
verb_dict = {
"say": say,
}
while True:
get_input()
网友评论