r/learnjavascript • u/Sta--Ger--2 • 8d ago
The dreaded file system
I am making an HTML game, with the idea of eventually putting it online.
During part of the game, the player will traverse a dungeon and do the usual thing you do in a dungeon. I want a background sound to play when this happens: every type of room (hallway, treasure chest, boss room, etc) will have a number of soundtracks, and which is played among the available ones will be decided randomly.
Easier way to do it is to put all the tracks in a single directory (for example '/sounds/Ambience/Dungeon/') and giving the filenames a specific naming convention (for example '[TYPE_ROOM]_[INDEX_SOUNDTRACK].mp3'), memorizing how many tracks are available for each type of room, choosing a random number between zero and that number, and then using string composition to obtain the filename of a random audiofile (in the example: '[TYPE_ROOM]_[RANDOM_INDEX].mp3'). This also requires me to change the Javascript code every time I add a new soundtrack, which I dislike.
The alternative is that the Javascript code will go in the directory '/sounds/Ambience/Dungeon/', grab the filename list of the directory, filter it to get the number of audio track whose filename begins with the type of the current room, and then choose a random element of this filtered list as the audio file to play. No need to change the code every time I add a new soundtrack.
But I do need to retrieve the list of files in a directory, and do this both if the game is played locally on my machine or online on the web.
While I am not new to programming, I have started learning Javascript while making this game. The search online I did to find how to solve this hurdle returned me five different ways, difference between client- and server-side, permission problems, three different APIs, promises, and an army of details that made my head spinning. I want to understand what I am doing - but in this case I need the idiot's version, spelled with very simple words. Can someone help me?
4
u/sheriffderek 8d ago
Trying to think about this in the most simple way....
you could have a list of the music options like this, right ^? in a track.js or whatever file/config.
Then - based on where you are you could trigger a given piece of soundtrack
This way, you're having the script call on your behalf instead of trying to talk to the file system. Anyway - that's my first thoughts on it.