Naoto Ida
Naoto Ida

Reputation: 157

Creating text dialogues for Javascript game

I have a game where you interact with NPCs, and they give multiple answers. I've searched for tutorials and demos, but they are all mostly Unity related.

I'm fairly new to Javascript, so I'm not sure where to begin with a text dialogue system that allows me (1)to show text on initial "hit"(which I've already been able to do), (2)give branching answers to that question, (3)and end on a certain line of text, (4)while being able to press the "Enter" key to continue the conversation.

The only way I can think of now is to use lots of If statements. But is there a much cleaner way of doing this?

Upvotes: 0

Views: 985

Answers (2)

Kevin Simper
Kevin Simper

Reputation: 1697

A way to do it would be to make a function, where the input is what the user choose:

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');

Another way would be store all the questions and answers in a object:

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');

Upvotes: 1

mjz19910
mjz19910

Reputation: 242

Yes look at this page about switches:
http://www.w3schools.com/js/js_switch.asp

Upvotes: 0

Related Questions