Ch029 - Game Mechanic: Adding Levels using Json
Game Mechanic: Adding Levels using Json
Here we will add the ability to use more than one level layout and have complete control over where we place our enemies, platforms and rewards (coins). We’ll explore a way to load in platforms and coins to collect from data objects in the JSON format.
Going over the Code
The code for a minimal example of the code for adding levels using json https://jamm-labs.github.io/ggcp/game-mechanic-more-levels/game.js
Create a variable in the list of global variables at the start of our code called level data
var leveldata;
Now create some data in the JSON style format. We could have these in external files but we’ll keep them in our game.js file to reduce the complexity of this example. All we need to know right now is we are using this approach to store the data for where our coins and platforms are. The JSON format is explained in more detail here https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON.
We can have a look at our entry for level one below.
var level1 = {"platforms":[{"image":"ground","x":0,"y":325},{"image":"grass:4x1","x":150,"y":240},{"image":"grass:4x1","x":250,"y":160}],
"coins":[{"image":"coin","x":0,"y":225},{"image":"coin","x":150,"y":200}]
This data contains two main sections, one for platforms and one for coins. Within those parts, there is an entry for the image name (which was defined in preload), and where it will appear on the screen. There is one for each level we want.
The next relevant bit of code is to choose which level
if (!currentLevel || currentLevel ===1){
leveldata = level1;
}
else if (currentLevel === 2 ){
leveldata = level2;
}
When generating the game area in creating we have added two loops to loop through each of lists of sprites, add them to the screen and add them to the relevant group.
for (var i = 0; i < leveldata.platforms.length; i++) {
var platform = platforms.create(leveldata.platforms[i].x, leveldata.platforms[i].y, leveldata.platforms[i].image);
platform.body.immovable = true;
var coin =coins.create(leveldata.coins[i].x, leveldata.coins[i].y, leveldata.coins[i].image);
}
That’s it. We hope you enjoy adding this game element to your game.