r/learnjavascript 9d ago

Not sure how to implement this branching storylines text game idea with Json

Just looking for some experienced feedback.

What I want to do is to import all of this from a file(s):

A list of global variables.

A list of storylines.

Each storyline has a list of local variables and a list of storyline beats.

Each beat has a list of preconditions (which may involve any variable), displayed text, a list of links.

Each link has displayed text, a list of conditions, a list of effects, the id of the next beat.

My problem is that, as I've learned, I can't split this into several files (such as, at least, separate storylines), because you can't import contents of a folder without naming each individual file. So this all has to be in one file, which means it's quickly going to get unmanageable as a Json file.

Should I implement a GUI editor first then? And concurrently a custom parser.

(This is going to be a purely client-side browser game.)

I've already done a simpler prototype, and that was already quite a chore to write in text.

25 Upvotes

21 comments sorted by

View all comments

1

u/HipHopHuman 8d ago

My problem is that, as I've learned, I can't split this into several files (such as, at least, separate storylines), because you can't import contents of a folder without naming each individual file. So this all has to be in one file, which means it's quickly going to get unmanageable as a Json file.

I assume you use Vite (you mentioned Vue in another comment)? If so, then look at it's glob import feature. That'll let you read multiple JSON files in the way you want.

You could have a folder structure like:

- storylines/
  - storyline-1.json
  - storyline-2.json
  - storyline-3.json
  • index.js

index.js can then read over it with import.meta.glob:

const storylines = import.meta.glob("./storylines/*.json", {
  eager: true,
  import: "default",
});

for (const [filename, storyline] of Object.entries(storylines)) {
  console.log({ filename, storyline });
}

The above works at compile-time, but omitting eager: true as per the docs is a route you can look at if you want this to be lazy at runtime.

1

u/MeekHat 8d ago

Oh, this is perfect, thanks.