Difference between revisions of "Rot.js tutorial, part 2"

From RogueBasin
Jump to navigation Jump to search
(Created page with "This is the second part of a rot.js tutorial. FIXME NOT COMPLETED! == Preparing the game turn engine == Our game is played within a web page; a rudimentary HTML file sh...")
 
Line 3: Line 3:
FIXME NOT COMPLETED!
FIXME NOT COMPLETED!


== Preparing the game turn engine ==
== The Player Character ==
 
Time to make some interesting interactive shinies! First, the player needs a decent representation. It would be sufficient to use a plain JS object to represent the player, but it is generally more robust to define the player via its constructor function and instantialize it.


Our game is played within a web page; a rudimentary HTML file should be sufficient.
By this time, you probably got used to the fact that some variable names start with an underscore. This is a relatively common technique of marking them ''private''. JavaScript does not offer true private variables, so this underscore-based nomenclature is just our useful way of marking stuff as "internal".
We would like to place the player to some spare floor tile: let's use exactly the same technique we used in Part 1 of this tutorial to place the boxes: just pick one free location from our list.


<div style="padding:5px; background-color:#eee; margin-bottom:2em;">
<div style="padding:5px; background-color:#eee; margin-bottom:2em;">
<syntaxhighlight lang="xml">
<syntaxhighlight lang="javascript">
<!doctype html>
var Player = function(x, y) {
<html>
    this._x = x;
     <head>
     this._y = y;
        <title>Ananas aus Caracas: rot.js tutorial game</title>
    this._draw();
        <script src="https://raw.github.com/ondras/rot.js/master/rot.js"></script>
}
        <script src="/path/to/the/game.js"></script>
 
     </head>
Player.prototype._draw = function() {
     <body onload="Game.init()">
    Game.display.draw(this._x, this._y, "@");
        <h1>Ananas aus Caracas</h1>
}
     </body>
 
</html>
Game.player = null;
 
Game._generateMap = function() {
    /* ...previous stuff... */
    this._createPlayer(freeCells);
};
 
Game._createPlayer = function(freeCells) {
     var index = Math.floor(ROT.RNG.getUniform() * freeCells.length);
     var key = freeCells.splice(index, 1)[0];
    var parts = key.split(",");
    var x = parseInt(parts[0]);
    var y = parseInt(parts[1]);
     this.player = new Player(x, y);
};
</syntaxhighlight>
</syntaxhighlight>
</div>
</div>


We are going to put all the game code in one file, to maintain simplicity (when making larger games, it is far more useful to split the code across several files). We do not want to pollute the global name space with our variables; that's why we wrap all our code in an object named "Game".
 
== Preparing the game turn engine ==
 
There will be two entities taking turns in our game: the Player Character and Pedro (The Enemy). To make things simple, these two will have the same speed, alternating their turns evenly. But even in this simple case, we can use the <code>ROT.Engine</code> timing framework to our advantage.
 
How does this work? After creating an instance of <code>ROT.Engine</code>, we feed it with all available ''actors''. The engine will then automatically take care about proper turn scheduling and letting these actors perform their actions.
 
Creating the engine is just a matter of adding a few lines to our code:


<div style="padding:5px; background-color:#eee; margin-bottom:2em;">
<div style="padding:5px; background-color:#eee; margin-bottom:2em;">
<syntaxhighlight lang="javascript">
<syntaxhighlight lang="javascript">
var Game = {
Game.engine = null;
    init: function() {}
 
Game.init = function() {
    this.engine = new ROT.Engine();
    this.engine.addActor(this.player);
    this.engine();
}
}
</syntaxhighlight>
</syntaxhighlight>

Revision as of 19:50, 12 December 2012

This is the second part of a rot.js tutorial.

FIXME NOT COMPLETED!

The Player Character

Time to make some interesting interactive shinies! First, the player needs a decent representation. It would be sufficient to use a plain JS object to represent the player, but it is generally more robust to define the player via its constructor function and instantialize it.

By this time, you probably got used to the fact that some variable names start with an underscore. This is a relatively common technique of marking them private. JavaScript does not offer true private variables, so this underscore-based nomenclature is just our useful way of marking stuff as "internal".

We would like to place the player to some spare floor tile: let's use exactly the same technique we used in Part 1 of this tutorial to place the boxes: just pick one free location from our list.

var Player = function(x, y) {
    this._x = x;
    this._y = y;
    this._draw();
}

Player.prototype._draw = function() {
    Game.display.draw(this._x, this._y, "@");
}

Game.player = null;

Game._generateMap = function() {
    /* ...previous stuff... */
    this._createPlayer(freeCells);
};

Game._createPlayer = function(freeCells) {
    var index = Math.floor(ROT.RNG.getUniform() * freeCells.length);
    var key = freeCells.splice(index, 1)[0];
    var parts = key.split(",");
    var x = parseInt(parts[0]);
    var y = parseInt(parts[1]);
    this.player = new Player(x, y);
};


Preparing the game turn engine

There will be two entities taking turns in our game: the Player Character and Pedro (The Enemy). To make things simple, these two will have the same speed, alternating their turns evenly. But even in this simple case, we can use the ROT.Engine timing framework to our advantage.

How does this work? After creating an instance of ROT.Engine, we feed it with all available actors. The engine will then automatically take care about proper turn scheduling and letting these actors perform their actions.

Creating the engine is just a matter of adding a few lines to our code:

Game.engine = null;

Game.init = function() {
    this.engine = new ROT.Engine();
    this.engine.addActor(this.player);
    this.engine();
}

Console output: ROT.Display

Being a JS app, our game can modify the HTML page in many ways. However, rot.js encourages only one kind of output: printing to its "tty console", which is represented by a HTML <canvas> tag. In order to draw anything, we first need to create this console and store it for later usage.

var Game = {
    display: null,

    init: function() {
        this.display = new ROT.Display();
        document.body.appendChild(this.display.getContainer());
    }
}

Note that this console has a default size of 80x25 cells; if we wanted different default dimensions, we would configure them via ROT.DEFAULT_WIDTH and ROT.DEFAULT_HEIGHT.

Generating a dungeon map

We will use one of rot.js's built-in map generators to create the game level. One of the design paradigms of rot.js is that people should not be forced to use some pre-defined data structures; this is why the generator is callback-based. We will pass our custom function to the generator; it will get called repeatedly during the process.

This might be a good time to check out the rot.js manual, which contains useful code samples and usage overview.

How should we store the resulting map data? We will use a very basic method of storage: an ordinary JS object ("hashmap"), indexed by strings (having the format "x,y"), values representing floor tiles. We are not going to store wall / solid cells.

NOTE: We are passing digCallback.bind(this) instead of just digCallback to the Digger. This is necessary to ensure that our callback is called within a correct context (activation object in ECMA parlance).

Game.map = {};
Game._generateMap = function() {
    var digger = new ROT.Map.Digger();

    var digCallback = function(x, y, value) {
        if (value) { return; } /* do not store walls */

        var key = x+","+y;
        this.map[key] = "·";
    }
    digger.create(digCallback.bind(this));
}

We still cannot see anything, because we have not written a single character to the display yet. Time to fix this: iterate through all the floor tiles and draw their visual representation.

Game._drawWholeMap = function() {
    for (var key in this.map) {
        var parts = key.split(",");
        var x = parseInt(parts[0]);
        var y = parseInt(parts[1]);
        this.display.draw(x, y, this.map[key]);
    }
}

Randomly generated boxes

Finally, let's create some boxes - potential ananas storage. We will hide the ananas in one of them in later parts of this tutorial. To place 10 random boxes around, we will leverage rot.js's Random number generator.

ROT.RNG can do a lot of stuff, but we need something simple: a random, evenly distributed number between zero (inclusive) and one (exclusive), just like the Math.random does. The proper way of doing this is calling ROT.RNG.getUniform().

We will store the empty cells in an array; for each box placed, we will pick a random empty cell, remove it from a list and mark that place as a box (asterisk) in our storage structure.

Game._generateMap = function() {
    var digger = new ROT.Map.Digger();
    var freeCells = [];

    var digCallback = function(x, y, value) {
        if (value) { return; } /* do not store walls */

        freeCells.push(key);
        var key = x+","+y;
        this.map[key] = "·";
    }
    digger.create(digCallback.bind(this));

    this._generateBoxes(freeCells);

    this._drawWholeMap();
};

Game._generateBoxes = function(freeCells) {
    for (var i=0;i<10;i++) {
        var index = Math.floor(ROT.RNG.getUniform() * freeCells.length);
        var key = freeCells.splice(index, 1)[0];
        this.map[key] = "*";
    }
};


And that's all for part 2. The whole working code is available at jsfiddle.net.