HTML and CSS Reference
In-Depth Information
e.preventDefault();
},
The primary tool method,
tile
, has the job to first check if the tile Canvas has been set up, and if not, calls
the
setupTiles
method to generate it. It then just shows that element, which blocks the rest of the screen and
waits for an event on the element to select a tile.
The
setupTiles
method creates a Canvas element, draws each tile in the tile map's spritesheet, and then
adds that element into the editor
controls
DOM element. It then adds an event handler to let the user select
a tile by clicking or touching it.
Finally, the
selectTile
method grabs the wanted tile frame by doing a little bit of math to calculate the
frame based on the size of the tiles and the size of the Canvas. It then checks that the frame is a valid frame and
if so sets the
activeTile
.
Running the editor in the browser should now allow you to choose different tiles that make up elements on
the page.
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
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);
});