Adding Level-Saving Support
The last task of the editor is to support the ability to save the level you’ve modified back to the server. On the client side, the code for doing this, as shown in Listing 19-7, is straightforward. This code should go in the same spot as usual at the bottom of the component definition in quintus_editor.js.
Listing 19-7: The editor save method
save: function() {
var levelName = prompt("Level Name?",this.levelFile);
if(levelName) {
$.post('/save',{ tiles: this.entity.collision.p.tiles,
level: levelName });
}
}
This code pops up the browser prompt dialog to ask the user for a filename and then posts that filename back to the server using $.post to send along the tiles data directly from the collision layer tile property.
On the server side, things are almost as easy. Using Express’s syntax for adding routes to the server, add the code in Listing 19-8 to the bottom of app.js.
Listing 19-8: The server save method
app.post('/save', function(req, res){
var data = _(req.body.tiles).map(function(row) {
return _(row).map(function(tile) { return Number(tile); });
});
fs.writeFile("public/data/" + req.body.level,
JSON.stringify(data));
res.send(201);
});
This code simply defines a route at /save that grabs the data that was posted in, transforms the tiles data into numbers, and then writes out a file. By default the posted tile data comes in correctly as an array of arrays, but each element in the array is a string, so it needs to be converted into a number. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access