Reputation: 1709
I am trying to write a small browser game in Typescript. So to start, I have a Scenario class that would need to load characters' dialogues based on scenario names. Here is how the Scenario class looks like:
export class Scenario extends Entity{
public characters: Character[] = [];
constructor(
public readonly scenarionName: string,
public readonly startDialogueId: string
) {
super();
}
public awake() {
this.loadCharacters();
}
private loadCharacters(){
this.characters = [];
// FIXME how can I dynamically load dialogues based on scenario name?
}
}
My idea was to have dialogues stored in JSON files, which would then be loaded based on the scenario name, which would also be a package name. Here how it looks:
In this case, I want to dynamically load 'npc.json' and 'player.json' into Scenario class based on the scenario name which in this case is a 'test'. In the future, there would be more scenarios and I would like to avoid hard coding. Can this be done in such a way and if so, how?
EDIT: the game would run in the browser.
Upvotes: 0
Views: 312
Reputation: 7852
Use fs
module to get the file names in a directory and read the contents of the files.
import fs from('fs');
export class Scenario extends Entity{
public characters: Character[] = [];
constructor(
public readonly scenarionName: string,
public readonly startDialogueId: string,
scenarioPath: string
) {
super();
}
public awake() {
this.loadCharacters();
}
private loadCharacters(){
this.characters = [];
const dialoguesDir = `${this.scenarioPath}/${this.scenarioName}/dialogues/`;
let dialogueContent;
fs.readdirSync(dialoguesDir).forEach(filePath => {
dialogueContent = fs.readFileSync(`${dialoguesDir}${filePath}`).toString();
// Do something with contents
});
}
}
Upvotes: 1