PHP编写的米德里比斯游戏脚本全过程
作者:转载自:更新时间:2009-9-14

米德里比斯

米德里比斯是一款文字游戏,玩家在游戏中得到一个简短的故事并用同一类型的不同单词替换主要类型的单词,从而创建同一个故事的更无聊的新版本。阅读以下文本:“I was walking in the park when I found a lake. I jumped in and swallowed too much water. I had to go to the hospital.” 开始用其他单词标记替换单词类型。开始和结束标记带有下划线用于阻止意外的字符串匹配。

清单 20. 用单词标记替换单词类型

  $text = "I was _VERB_ing in the _PLACE_ when I found a _NOUN_.
  I _VERB_ed in, and _VERB_ed too much _NOUN_.  I had to go to the _PLACE_.";

接下来,创建几个基本单词列表。对于本例,我们也不会做得太复杂。

清单 21. 创建几个基本单词列表

  $verbs = array('pump', 'jump', 'walk', 'swallow', 'crawl', 'wail', 'roll');
  $places = array('park', 'hospital', 'arctic', 'ocean', 'grocery', 'basement',
  'attic', 'sewer');
  $nouns = array('water', 'lake', 'spit', 'foot', 'worm',
  'dirt', 'river', 'wankel rotary engine');

现在可以重复地评估文本来根据需要替换标记。

清单 22. 评估文本

  while (preg_match("/(_VERB_)|(_PLACE_)|(_NOUN_)/", $text, $matches)) {
  switch ($matches[0]) {
  case '_VERB_' :
  shuffle($verbs);
  $text = preg_replace($matches[0], current($verbs), $text, 1);
  break;
  case '_PLACE_' :
  shuffle($places);
  $text = preg_replace($matches[0], current($places), $text, 1);
  break;
  case '_NOUN_' :
  shuffle($nouns);
  $text = preg_replace($matches[0], current($nouns), $text, 1);
  break;
  }
  }
  echo $text;

很明显,这是一个简单而粗糙的示例。单词列表越精确,并且花在基本文本上的时间越多,结果就越好。我们已经使用了文本文件创建名称列表及基本单词列表。使用相同原则,我们可以创建按类型划分的单词列表并使用这些单词列表创建更加变化多端的米德里比斯游戏。