1
\$\begingroup\$

I'm new to JS game programming. In the past, when coding games (in Java), I tend to make separate files for configuration and game data (maps, character stats, etc). This is for separation of code and data. How can I effectively implement this on JS?

EDIT: This is for browsers only.

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

In this answer I'm going to assume that your game is a web game, if it's a locally running game in a Node.JS wrapper or something similar then the answer would be a little different and I'll edit the answer.

To have a data file that is separate from the code that runs it you can create a JSON file and then load it from the code.

First let us define a file called classes.json that looks like this:

{ "classList":[{ "name": "Wizard", "health": 5 },{ "name": "Rogue", "health": 23 }] }

Now load the data file by requesting it from the site:

var request = new XMLHttpRequest();
request.addEventListener("load", function requestListener(){
    //TADA! Now I have the class data.
    var classes = JSON.parse(this.responseText);
    var wizard = classes.classList[0];
    var rogue = classes.classList[1];
});
request.open("GET", "http://www.userx01s-game.com/classes.json");
request.send();


Doing it this way also allows you to delay loading the classes information until it is absolutely necessary to have it, thus speeding the initial load of the game.


P.S. For more information about ajax requests you can check out https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest


EDIT: Here I will also include an example of if you don't want to use AJAX and instead just want to have the data available upon initial page load.

First create a file called classes.js that looks like this:

var classList = [{ "name": "Wizard", "health": 5 },{ "name": "Rogue", "health": 23 }];

Then in your HTML you include this file like normal:

<html>
  <head>
    <script src="classes.js" ></script>
    <script src="game.js" ></script>
  </head>
</html>

Finally in your game use the data as a standard JavaScript object:

var wizard = classList[0];
var rogue = classList[1];
\$\endgroup\$
2
  • \$\begingroup\$ Yes, this is a browser game. Is loading them via AJAX better than loading them along with the web document? \$\endgroup\$
    – userx01
    Commented Oct 17, 2015 at 10:01
  • \$\begingroup\$ It depends on the size of your game. If the game is very large and includes a lot of data files then the initial load is going to take awhile and generally every second added on to the load time takes out a few more users. Alternatively if the data files are small enough you could just include them in the initial load. I'll edit the original answer to include an example now. \$\endgroup\$ Commented Oct 18, 2015 at 1:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .