I’m new to JavaScript. I’ve looked for an answer to my problem, but can’t figure this out.
Likewise, I have an array of different options (for a text adventure game) that I want to import into the main JS script. The issue is that I am calling different options from the array in the main script, and it’s not working.
The answers I found on the internet would work for importing functions from a module into HTML code, but that isn’t what I’m looking for.
Here is the code that is working:
const textElement = document.getElementById('text');
const buttonOptionsElement = document.getElementById('buttonOptions');
// keep track of what the character has on them
let state = {}
// function to start the game
function startGame() {
state = {}
showTextNode(1)
}
function showTextNode(textNodeIndex) {
const textNode = textNodes.find(textNode => textNode.id === textNodeIndex)
textElement.innerText = textNode.text
while (buttonOptions.firstChild) {
buttonOptions.removeChild(buttonOptions.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))
buttonOptions.appendChild(button)
}
})
}
function showOption(option) {
return option.requiredState == null || option.requiredState(state)
}
// function to get the element clicked
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: 'First scenario',
options: [
{
text: 'Take goo',
setState: { blueGoo: true},
nextText: 2
},
{
text: 'leave the goo',
}
]
},
{
id: 2,
text: 'this is the second scenario.',
options: [
{
text: 'trade the goo for a sword',
requiredState: (currentState) => currentState.blueGoo,
setState: { blueGoo: false, sword: true},
nextText: 3
}
]
startGame();
The code that isn’t working is simply the same thing, but instead of having the textNodes array in the main.js, I have it in a separate file. I import it in place of the const textNodes = [{},...,{}] with the following line:
import { textNodes } from './modules/scenario.js'
Advertisement
Answer
Ok I found the issue… It’s ridiculous, it’s just that in the HTML I typed type="modules" instead of type="module".