Initial commit

This commit is contained in:
2020-07-06 00:04:44 +02:00
commit dbb13b8050
7 changed files with 159 additions and 0 deletions

20
src/entity.js Normal file
View File

@@ -0,0 +1,20 @@
export class Entity {
constructor(id, text) {
this.id = id;
this.text = text;
}
}
export class Node extends Entity {
constructor(id, text, choices) {
super(id, text);
this.choices = choices;
}
}
export class Choice extends Entity {
constructor(id, text, nextNode) {
super(id, text);
this.nextNode = nextNode;
}
}

58
src/index.js Normal file
View File

@@ -0,0 +1,58 @@
const jsonContent = [{
id: 'node-1',
text: 'Node 1',
choices: [{
id: 'choice-1',
text: 'Choice 1',
nextNode: 'node-2'
}, {
id: 'choice-2',
text: 'Choice 2',
nextNode: 'node-exit'
}]
}, {
id: 'node-2',
text: 'Node 2',
choices: [{
id: 'choice-3',
text: 'Choice 3',
nextNode: 'node-exit'
}, {
id: 'choice-4',
text: 'Choice 4',
nextNode: 'node-exit'
}]
}, {
id: 'node-exit',
text: 'Game over!'
}];
function printChoices(node) {
return node.choices.forEach(choice => {
const newBtn = document.createElement('button');
newBtn.onclick = () => selectChoice(choice.id);
newBtn.innerHTML = choice.text;
newBtn.classList.add('choice-btn');
document.getElementById('choices').appendChild(newBtn);
});
}
function selectChoice(choiceId) {
console.log('Click on choice ', choiceId);
const allChoices = jsonContent.flatMap(node =>
!node.choices ? [] : node.choices
);
const selectedChoice = allChoices.find(choice => choice.id === choiceId);
const nextNode = jsonContent.find(node => node.id === selectedChoice.nextNode);
updateActiveNode(nextNode);
}
function updateActiveNode(node) {
document.getElementById('active-node').innerHTML = node.text;
document.getElementById('choices').innerHTML = '';
printChoices(node);
}
window.onload = () => {
updateActiveNode(jsonContent[0]);
}