在管理不同的对象及其关系时,面向对象是非常有用的。当你开发具有不同角色和特征的游戏时,这是特别有用的。

我们来看一个示例项目,该项目展示了如何在游戏开发中使用类。

要开发的游戏是一个老式的基于文本的冒险游戏。

下面是函数处理输入和简单的解析。

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)

verb_dict = {
  "say": say,
}

while True:
  get_input()
======
结果:
: say Hello!
You said "Hello!"
: say Goodbye!
You said "Goodbye!"

: test
Unknown verb test

上面的代码从用户处获取输入,并尝试将第一个单词与 verb_dict 中的命令进行匹配。如果找到匹配,则调用相应的功能。
这让我想起了以前我写过的一个作业检查程序,那个程序后来被我用Delphi和C#又都重写了两次,分别用不通的查找方式
其实delphi真的挺好用的,编译出来的体积又小,hash查找极速,且带ui界面,可惜国内教程实在太少,不太友好.对于我这样的小白来说还是难上手
偏题了

其实这个例子中

if len(command) >= 2:

这一句可以用来检查用户输入的学生数量的.

split() 通过指定分隔符对字符串进行切片

str = "Line1-abcdef \nLine2-abc \nLine4-abcd";
print str.split( );       # 以空格为分隔符,包含 \n
print str.split(' ', 1 ); # 以空格为分隔符,分隔成两个
以上实例输出结果如下:
['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
['Line1-abcdef', '\nLine2-abc \nLine4-abcd']

上面那个例子我玩了一下,作者对于运用已经十分熟练了,所以写出来的逻辑对于新手有点绕,我个人重新写了一下,以加深理解,其实换成这样写看起来就容易的多了:

def get_input():
  command = input(": ").split()
  word = command[0]
  if word in verb_dict:
    verb = verb_dict[word]
  else:
    print("Unknown verb {}".format(word))
    return

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


def say(noun_word):
  print ('You said "{}"'.format(noun_word))

verb_dict = {
  "say" : say,
}

while True:
  get_input()

我上面这样写,其一关键词一一对应,不容易误解,其二我将if len的print语句删除了,直接写的调用say方法,其三say方法我把return改为了print

下一步是使用类来表示游戏对象。

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)

我们创建了一个 Goblin 类,它继承自 GameObjects 类。

我们还创建了一个新的函数 examine,它返回对象的描述。

现在我们可以添加一个新的 “examine” 动词到我们的字典,并尝试一下!

verb_dict = {
  "say": say,
  "examine": examine,
}

将此代码与前一个示例中的代码结合起来,然后运行该程序。

: say Hello!
You said "Hello!"

: examine goblin
goblin
A foul creature

: examine elf
There is no elf here.
:

这段代码补充了 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 = thing.health - 1
      if thing.health <= 0:
        msg = "You killed the goblin!"
      else: 
        msg = "You hit the {}".format(thing.class_name)
  else:
    msg ="There is no {} here.".format(noun) 
  return msg
结果:

: hit goblin
You hit the goblin

: examine goblin
goblin
 A foul creature
It has a wound on its knee.

: hit goblin
You hit the goblin

: hit goblin
You killed the goblin!

: examine goblin
A goblin

goblin
 A foul creature
It is dead.
:

这只是一个简单的例子。
你可以创造不同的类(例如精灵,兽人,人类),与他们作战,使他们相互对抗,等等。
下次玩过了再来更新...我还没玩

今天玩了一下,感觉稍微有点绕,处理了一下之后发现其实只是在字典里添加了指令,然后由这个字典里的指令调用函数
整理了一下完整代码如下:

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):
  def __init__(self,name):
    self.class_name = "哥布林"
    self.health = 3
    self._desc = "一个丑陋的生物"
    super().__init__(name)
    print(self.class_name + "被创建")

  @property
  def desc(self):
    if self.health >= 3:
      return self._desc
    elif self.health == 2:
      health_line = "它的膝盖有一个伤口"
    elif self.health == 1:
      health_line = "他左边的胳膊已经被斩断!"
    elif self.health == 0:
      health_line = "这只哥布林已经死了"
    return self._desc + "\n" + health_line
  @desc.setter
  def desc(self,value):
    self._desc = value
goblin = Goblin(1)
def hit(noun):
  if noun in GameObject.objects:
    thing = GameObject.objects[noun]
    if type(thing) == Goblin:
      thing.health -= 1
      if thing.health <= 0:
        msg = "你杀死了这只哥布林"
      else:
        msg = "你攻击了{}".format(thing.class_name)
  else:
    msg = "这里没有{}".format(noun)
  return msg

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

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)

verb_dict = {
  "say": say,
  "find": examine,
  "hit" : hit
}


while True:
  get_input()
======
结果:
哥布林被创建
: find 哥布林
哥布林
一个丑陋的生物
: hit 哥布林
你攻击了哥布林
: find 哥布林
哥布林
一个丑陋的生物
它的膝盖有一个伤口
: hit 哥布林
你攻击了哥布林
: find 哥布林
哥布林
一个丑陋的生物
他左边的胳膊已经被斩断!
: hit 哥布林
你杀死了这只哥布林
: find 哥布林
哥布林
一个丑陋的生物
这只哥布林已经死了
最后修改:2022 年 12 月 05 日
如果觉得我的文章对你有用,请随意赞赏