requiredState: (currentState) => currentState.StateHere
optionButtonsElement
<div class="container"> <div id="text">Text</div> <div id="option-buttons" class="btn-grid"> <button class="btn">Option 1</button> <button class="btn">Option 2</button> <button class="btn">Option 3</button> <button class="btn">Option 4</button> </div> </div>
const textElement = document.getElementById("text"); const optionButtonsElement = document.getElementById("option-buttons"); let state = {}; function startGame() { state = {}; showTextNode(1.1); } function showTextNode(textNodeIndex) { const textNode = textNodes.find((textNode) => textNode.id === textNodeIndex); textElement.innerText = textNode.text; while (optionButtonsElement.firstChild) { optionButtonsElement.removeChild(optionButtonsElement.firstChild); } textNode.options.forEach((option) => { if (showOption(option)) { const button = document.createElement("button"); button.innerText = option.text; button.classList.add("btn"); button.addEventListener("click", () => selectOption(option)); optionButtonsElement.appendChild(button); } }); } function showOption(option) { return option.requiredState == null || option.requiredState(state); } function selectOption(option) { const nextTextNodeId = option.nextText; if (nextTextNodeId <= 0) { return startGame(); } state = Object.assign(state, option.setState); showTextNode(nextTextNodeId); } const textNodes = [ { id: 1.1, text: "What is going on? Where am I? No. That's not what I need to ask. A better question would be...", options: [ { text: "Who... am I?", nextText: 1.2 } ] }, { id: 1.2, text: "I, I don't know. I can't remember. I need to survive. I need food, water, and shelter the basics of survival. Maybe I'll remember more in time. Until then, I must survive.", options: [ { text: "And survive I will!", setState: { Survivalist: true }, nextText: 1.3 }, { text: "Later...", nextText: 1.3 } ] }, { id: 1.3, text: "PLACEHOLDER" } ]; startGame();
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)