为Javascript游戏创建文本对话

Creating text dialogues for Javascript game

本文关键字:文本 对话 创建 游戏 Javascript      更新时间:2023-09-26

我有一个游戏,你和NPC互动,他们会给出多个答案。我搜索了教程和演示,但它们大多与 Unity 相关。

我对Javascript相当陌生,所以我不确定从哪里开始文本对话系统允许我 (1( 在初始"命中"时显示文本(我已经能够做到(,(2( 为该问题给出分支答案,(3( 并在某一行文本上结束,(4(同时能够按"Enter"键继续对话。

我现在能想到的唯一方法是使用大量的 If 语句。但是有没有更清洁的方法呢?

一种方法是创建一个函数,其中输入是用户选择的:

function askNPC(question) {
  switch(question){
    case 'buy sword':
      return 'here you go!'; 
    break;
    case 'sell fish':
      return 'here you go!';
    break;
  }
}
var answer = askNPC('buy sword');
var answer = askNPC('sell fish');

另一种方法是将所有问题和答案存储在一个对象中:

var questions = {
  'buy sword': 'here you go',
  'sell fish': 'thank you'
}
function askNPC(question){
  if(typeof questions[question] !== "undefined"){
    return questions[question];
  } else {
    return 'Did not understand you question!';
  }
}
var answer = askNPC('buy sword');
var answer = askNPC('sell fish');
是的,

看看这个关于开关的页面:
http://www.w3schools.com/js/js_switch.asp