Kazuma_Itsuchi
New Coder
I am making a text game using HTML, CSS, and Javascript. However, I can't seem to get States to work properly. Am I missing something simple, or am I simply overestimating the use of States?
HTML:
<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>
CSS:
*, *::before, *::after {
box-sizing: border-box;
}
body {
padding: 0;
margin: 0;
display: flex;
justify-content: center;
align-items: center;
width: 100vw;
height: 100vh;
background-color: #333;
}
.container {
width: 800px;
max-width: 80%;
background-color: white;
padding: 10px;
border-radius: 5px;
box-shadow: 0 0 10px 2px;
}
.btn-grid {
display: grid;
grid-template-columns: repeat(2, auto);
gap: 10px;
margin-top: 20px;
}
.btn {
background-color: hsl(200, 100%, 50%);
border: 1px solid hsl(200, 100%, 30%);
border-radius: 5px;
padding: 5px 10px;
color: white;
outline: none;
}
.btn:hover {
border-color: black;
}
JavaScript:
const textElement = document.getElementById('text')
const optionButtonsElement = document.getElementById('option-buttons')
let state = {}
function startGame() {
state = {}
showTextNode(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,
text: "You wake up to a roaring sound. You feel as if you have heard this particular roar before, but can't remember where.",
options: [
{
text: "Look around (use base character)",
setState: { roomKnowledge: true },
nextText: 2
},
{
text: "Try to Remember (use custom character)",
setState: { customCharacter: true },
nextText: 2
},
],
},
{
id: 2,
requiredState: (currentState) => currentState.roomKnowledge,
text: "1",
},
{
id: 2,
requiredState: (currentState) => currentState.customCharacter,
text: "2",
}
]
startGame()