I’ve been working on quite a long and poorly organized program for a little while now, and I’ve run into a problem I haven’t been able to find a solution for this.
The relevant code snippets are (I think):
state = {
letters: [],
writing: Number
writing_content: {}
}
const characters = ["bunch","of","characters"]
function finalLetter() {
let letter = {
recipient: characters[state.writing],
}
letter = Object.assign(letter, deepCopy(state.writing_content))
return letter
}
function deepCopy(object) {
return JSON.parse(JSON.stringify(object))
}
function showTextNode(TextNodeID) {
previousTextNode = currentTextNode
currentTextNode = textNodeIndex
const textNode = textNodes.find(textNode => textNode.id === textNodeIndex)
while (textNode.title.includes("undefined")){
textNode.title = textNode.title.replace("undefined", eval(textNode.updateTitle[i])).replace("_", " ")
i++
}
textNode.options.forEach(option => {
if (showOption(option)) {
const button = document.createElement('button')
button.innerText = option.text
if (option.leave) option.nextText = outsideNode
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 (Object.hasOwn(option, "setState")) {
for (i=0; i<option.setState.category.length;i++) {
if (option.setState.category[i] != "general") state[option.setState.category[i]] = Object.assign(state[option.setState.category[i]], option.setState.changes[i])
else state = Object.assign(state, option.setState.changes[i])
}
}
if (option.send) sendLetter(state.current_letter)
showTextNode(nextTextNodeId)
}
let textNodes = [
{
id: 99919,
title: `Letter to ${characters[state.writing]}`,
updateTitle: ["characters[state.writing]"],
text: "Do you wish to send it immediately?",
options: [
{
text: "No",
setState: {
category:["general"], changes:{letters: state.letters.concat(finalLetter()),
}},
leave: true,
nextText: outsideNode
}
]
}
]
(This is borderline unreadable in the editor. I hope it’ll look better in the post)
The problem is quite simple; After I click the “No” button, it does everything it’s supposed to, but state.letters remains empty. I’ve checked that the whole “setState” stuff works with other options, and finalLetter() works as well when it’s called on its own.
I’ve tried moving the function call into selectOption(option), but that didn’t help.
I must admit that I have been learning JavaScript on the go, as I started with a tutorial specific for basic text adventures and tried to hammer my own system into it without really knowing how the language works, and it has caused me grief in the past, but I’ve never been so clueless as I am now.