# Creating a dialogue tree for your game

> Learn how to create a dynamic dialogue tree using Coherent Gameface. This guide takes you through the steps to implement interactive branching conversations in your game's UI.

> Documentation index: https://coherent-labs.com/llms.txt lists every page of this documentation as Markdown; the full text is in https://coherent-labs.com/llms-full.txt.

Source: https://coherent-labs.com/blog/uitutorials/dialogue-tree/

## Creating a dialogue tree for your game

ui tutorials

10/1/2024

Mihail Todorov

1. Where to find the working example
2. Creating our dialogue tree
3. Setting up our dialogue UI
4. Selecting an option
   1. Creating the typing effect
   2. Creating the response options
   3. Adding interactions
   4. Tying everything together
5. In conclusion

Creating a dialogue tree is essential for immersive storytelling in games, allowing for dynamic conversations between players and NPCs. Coherent Gameface, with its powerful UI system, offers a robust way to build and display these dialogue systems. In this tutorial, we’ll walk through how to create a dialogue tree from scratch using Gameface, helping you bring more interactive experiences into your game.

## Where to find the working example

You can find the whole project source in the `${Gameface package}/Samples/uiresources/UITutorials/DialogueTree` folder.

## Creating our dialogue tree

The first thing we need to do is create our dialogue tree. For this example we’ll be creating a dialogue tree that has 2 to 3 options per dialogue and will be at least 5 levels deep.

Once we have that we need to present it in a format that will benefit us the most. This is why for this particular example we’ll make it into a JavaScript object in the following format

```js
{
    text: "",
    responses: [
        {
            text: "",
            dialogueNumber: 0,
        }
    ]
}
```

Where `text` is the guild master question, and responses are the possible choices that the player would have. In the responses `dialogueNumber` refers to the guild master question that will be shown when the response is chosen and it’s index in the array.

For this example we’ve added the dialogue tree as JavaScript array as we are mocking the interactions, but in a game it should come from the backend/game.

```js
const dialogueTree = [
    {
        text: "Ah, welcome! I hear you've come seeking work. There's a mission available, but it's not for the faint of heart. What do you say? Interested?",
        responses: [
            {
                text: "Yes, I'm ready for anything.",
                dialogueNumber: 1,
            },
            {
                text: "Tell me more before I decide.",
                dialogueNumber: 2,
            },
            {
                text: "I'm not sure. What's the reward?",
                dialogueNumber: 3,
            }
        ]
    },
    {
        text: "Good to hear! There's a band of marauders causing trouble near the northern pass. We need someone to deal with them. Do you accept?",
        responses: [
            {
                text: "I'll take care of it.",
                dialogueNumber: 4,
            },
            {
                text: "Is there any backup for this mission?",
                dialogueNumber: 5,
            }
        ]
    },
    {
        text: "The mission involves taking down a notorious bandit leader. They've terrorized nearby villages for weeks. You'll need to be clever as well as strong. What do you think?",
        responses: [
            {
                text: "I'll do it. The villages need help.",
                dialogueNumber: 6,
            },
            {
                text: "This sounds dangerous. How many people are we talking about?",
                dialogueNumber: 7,
            }
        ]
    },
    {
        text: "The reward? Well, aside from the gratitude of the villages, there's gold and a rare item—a relic with great power.",
        responses: [
            {
                text: "I'm in. Tell me what needs to be done.",
                dialogueNumber: 8,
            },
            {
                text: "A relic? What kind of power are we talking about?",
                dialogueNumber: 9,
            }
        ]
    },
    {
        text: "Excellent. You leave immediately. I'll mark the location on your map. Be careful out there.",
        responses: [
            {
                text: "Understood. I'm heading out now.",
                dialogueNumber: null,
            },
            {
                text: "Any advice before I go?",
                dialogueNumber: 10,
            }
        ]
    },
    {
        text: "We're sending only you. The Guild is stretched thin right now. Do you still want to proceed?",
        responses: [
            {
                text: "Yes, I'll manage.",
                dialogueNumber: null,
            },
            {
                text: "No, I need support.",
                dialogueNumber: null,
            }
        ]
    },
    {
        text: "Good. You'll be a hero to these people.",
        responses: [
            {
                text: "I'll make sure of it.",
                dialogueNumber: null,
            }
        ]
    },
    {
        text: "The leader has a handful of loyal fighters, but their numbers are small. A direct fight might not be wise.",
        responses: [
            {
                text: "I'll take them by surprise, then.",
                dialogueNumber: null,
            },
            {
                text: "What if I negotiate with them?",
                dialogueNumber: 11,
            }
        ]
    },
    {
        text: "Head to the northern pass and find the marauders. The relic is rumored to be in their possession.",
        responses: [
            {
                text: "I'll find it and take them down.",
                dialogueNumber: null,
            },
            {
                text: "Is there a safe way to retrieve the relic without fighting?",
                dialogueNumber: 12,
            }
        ]
    },
    {
        text: "It's an ancient charm said to grant enhanced strength in battle. Many would pay a high price for it.",
        responses: [
            {
                text: "That's good enough for me. I'll take the mission.",
                dialogueNumber: 8,
            },
            {
                text: "That sounds too dangerous for me. I'll pass.",
                dialogueNumber: null,
            }
        ]
    },
    {
        text: "Negotiating with bandits? You'd be risking everything. But if that's what you believe is right, I won't stop you.",
        responses: [
            {
                text: "I'll find a way to end this peacefully.",
                dialogueNumber: null,
            },
            {
                text: "On second thought, I'll go with the ambush.",
                dialogueNumber: null,
            }
        ]
    },
    {
        text: "Perhaps, if you're stealthy enough. But I doubt they'll let you walk out with it once they see you.",
        responses: [
            {
                text: "I'll risk it. I'm good at staying unseen.",
                dialogueNumber: null,
            },
            {
                text: "I'll think of another approach.",
                dialogueNumber: null,
            }
        ]
    }
];
```

## Setting up our dialogue UI

Before we make the logic for the dialogues we first need to set up the visual part. That would include creating our HTML and styling using the CSS.

In our HTML we have two major containers - the `.npc-dialogue-container` and the `.player-options-container` which will be inside the **npc-dialogue-container**

```html
<html lang="en">
  <head>
    <link rel="stylesheet" href="./css/style.css" />
  </head>
  <body>
    <div class="npc-dialogue-container">
      <div class="npc-dialogue" cohinline>
        <span class="guild-master">Guild Master:</span>
        <span class="guild-master-text">
          "Ah, welcome! I hear you've come seeking work. There's a
          mission available, but it's not for the faint of heart. What
          do you say? Interested?"</span
        >
      </div>
      <div class="player-options-container">
        <p class="player-option" id="0" tabindex="1">
          Yes, I'm ready for anything.
        </p>
        <p class="player-option" id="1" tabindex="1">
          Tell me more before I decide.
        </p>
        <p class="player-option" id="2" tabindex="1">
          I'm not sure. What's the reward?
        </p>
      </div>
    </div>
    <div class="help-text">Press Enter to select the dialogue option</div>
    <script src="./js/cohtml.js"></script>
    <script src="./js/dialogue.js"></script>
    <script src="./js/index.js"></script>
  </body>
</html>
```

Here you can see in this HTML snippet, that we are using the first question and responses from the dialogue tree array. The reason is that we want it to be availabe when you load the sample, but in a real use-case scenario you can add the data using JavaScript.

Something else that we need to note here is that we add to the `player-options` an id that will be the `dialogueNumber` from the responses.

Once that is done we’ll simply style or UI by adding the following `style.css`

```css
@font-face {
  font-family: "IM FELL Double Pica SC";
  src: url(../assets/im-fell-double-pica.sc.ttf);
}

body {
  margin: 0;
  padding: 0;
  font-family: "IM FELL Double Pica SC";
  width: 100vw;
  height: 100vh;
  color: white;
  font-size: 2.4vh;
  background-image: url(../assets/guild-master.jpg);
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
}

.npc-dialogue-container {
  position: absolute;
  bottom: 3%;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
}

.npc-dialogue {
  width: 80%;
  height: 13vh;
  display: flex;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.7);
  padding: 0 3vh;
  border-image-slice: 27;
  border-image-width: 40px;
  border-image-outset: 0;
  border-image-repeat: stretch;
  border-image-source: url(../assets/dialogue-border.png);
  border-radius: 10px;
}

.guild-master {
  width: 20%;
  color: #eecd9c;
}

.guild-master-text {
  width: 80%;
}

.player-options-container {
  position: absolute;
  bottom: 120%;
  right: 7%;
}

.player-option {
  border-image-slice: 15;
  border-image-width: 40px;
  border-image-outset: 0;
  border-image-repeat: stretch;
  border-image-source: url(../assets/dialogue-border.png);
  padding: 2vh;
  width: 40vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-image: linear-gradient(
    to right,
    transparent,
    black 50%,
    transparent
  );
}

.player-option:focus {
  background-image: linear-gradient(
    to right,
    transparent,
    #ac864d 50%,
    transparent
  );
}

.player-option:hover {
  background-image: linear-gradient(
    to right,
    transparent,
    #ac864d 50%,
    transparent
  );
}

.help-text {
  position: absolute;
  top: 15%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: black;
  padding: 1vh;
}
```

## Selecting an option

### Creating the typing effect

In many games where you have dialogues the text appears as if it was typed on screen. To mimic this we’ll create a function called `writeText` and add the following code

```js
const guildMaster = document.querySelector(".guild-master-text");
let interval, skipText = false;

function writeText(dialogue) {
  return new Promise((resolve) => {
    let index = 0;

    interval = setInterval(() => {
      if (index === dialogue.text.length || skipText) {
        skipText = false;
        resolve(dialogue);
        clearInterval(interval);
        interval = null;
        return;
      }

      guildMaster.textContent += dialogue.text[index];
      index++;
    }, 25);
  });
}
```

Here we return a `Promise` so that when the text finishes typing out, we can show the options for a response. We then set an interval and on each iteration we add a letter to the `guildMaster` element text content. Once all of the letters are typed out we clear the interval and resolve the promise.

We’ll also use a flag `skipText`, which will stop the interval and resolve the promise. This will allow us later to skip the text typing out if we want.

### Creating the response options

To create the response options we’ll first set a template

```js
function createDialogueOptionTemplate(text, id) {
  return `<p class="player-option" id="${id}" tabindex="1">
                ${text}
            </p>`;
}
```

where we set the `id` and the `text`.

Then we create a function to add the options

```js
const options = document.querySelector(".player-options-container");

function addOptions(dialogue) {
  clearInterval(interval);
  interval = null;
  guildMaster.textContent = dialogue.text;
  options.innerHTML = dialogue.responses.reduce(
    (acc, response, index) => {
      acc += createDialogueOptionTemplate(response.text, index);
      return acc;
    },
    ""
  );

  options.firstChild.focus(); //We focus on the first option so it's easier to interact later using the keyboard
}
```

And finally we set the guild master dialogue along with the options

```js
function setDialogue(dialogue) {
  guildMaster.textContent = ""; //Clear the previous text
  options.textContent = ""; //Clear the options as well
  writeText(dialogue.text).then(addOptions);
}
```

### Adding interactions

For this example we’ll be using both the keyboard and the mouse to select a response. This is why we’ll add two event listeners - for `click` and for `keydown`

```js
document.addEventListener("click", () => {});

document.addEventListener("keydown", () => {});
```

In our `click` event we need to check if the item that we are clicking is a response option and if the text is being typed out we want to skip it.

First we’ll create a function that handles the option selection.

```js
function selectOption(element) {
  const id = element.id;
  engine.trigger("selectDialogue", id);
}
```

Where we get the id that we’ve set to correspond to the correct dialogue index and trigger an event in our game with it.

Now in the `click` event handler we do the following:

```js
document.addEventListener("click", ({ target }) => {
  if (target.closest(".player-options-container")) {
    selectOption(target);
    return;
  }

  if (interval) {
    skipText = true;
    return;
  }
});
```

We check if the clicked element is an option and then run the function we’ve created. And we also check if the interval is set. If it is we change the `skipText` flag to true and it will resolve the promise in the `writeText` function.

Now we can do the same in the `keydown` handler

```js
document.addEventListener("keydown", ({ keyCode }) => {
  if (keyCode === 13) { // ENTER key
    if (document.activeElement.closest(".player-options-container")) {
      selectOption(document.activeElement);
      return;
    }

    if (interval) {
      skipText = true;
      return;
    }
  }
});
```

We check if the user pressed enter, then we check if the current focused item is from the options and we select it.

Since we don’t have the ability to choose which option, we’ll also add the following logic to our `keydown` handler:

```js
document.addEventListener("keydown", ({ keyCode }) => {
  if (keyCode === 13) {
    if (document.activeElement.closest(".player-options-container")) {
      selectOption(document.activeElement);
      return;
    }

    if (interval) {
      skipText = true;
      return;
    }
  }

  if (keyCode === 38) { //Arrow key down
        const nextSibling = document.activeElement.previousElementSibling;

        if (nextSibling) nextSibling.focus();
        else options.firstChild.focus();
  }

  if (keyCode === 40) { //Arrow key up
        const prevSibling = document.activeElement.nextElementSibling;
        if (prevSibling) prevSibling.focus();
        else options.lastChild.focus();
  }
});
```

Here we check if the arrow up or down keys are pressed and if they are we focus on the next or previous sibling, depending on the key. If there is no sibling, meaning that the element is the first or last we just focus the last or first element so we can loop it around.

### Tying everything together

We’ve added all of our logic, but even if we try to select an option nothing will happen as we haven’t “hooked it up to the game” yet. In this scenario we would listen for the `"selectDialogue"` event on our backend and then trigger an event from the game that will send us the correct text.

Since we don’t have a game we’ll mock that by listening for said event and getting the data from the `dialogueTree` array like so:

```js
engine.whenReady.then(() => {
  engine.on("selectDialogue", (id) => {
    let index =
      dialogueTree[currentDialogueIndex].responses[id].dialogueNumber;
    if (!index) index = 0;
    engine.trigger("changeDialogue", dialogueTree[index], index);
  });

  engine.on("changeDialogue", (dialogue, index) => {
    currentDialogueIndex = index;
    setDialogue(dialogue);
  });
});
```

We wait for the engine object to be available, then we get the text from the `dialogueTree` when the event is triggered, here we need to check if the `dialogueNumber` is `null` and if it is we go back to the first text. And finally we trigger another event that will be listening on the frontend to change the text.

## In conclusion

By following this guide, you’ve now learned how to create a functional dialogue tree using Coherent Gameface. With this system in place, your games can have branching conversations that enhance player immersion and choice. As you get more comfortable with Gameface, you can expand and customize your dialogue trees to meet the narrative needs of your game. Stay creative and keep exploring the possibilities Gameface brings to UI design!

## On this page
