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

From RogueBasin
Jump to navigation Jump to search
(From the rot.js source, 38 is VK_UP, and goes [0, -1], which is up (rather than upper-left))
 
(15 intermediate revisions by 3 users not shown)
Line 1: Line 1:
This is the second part of a [[rot.js tutorial]].
This is the second part of a [[rot.js tutorial]].
FIXME NOT COMPLETED!


== The Player Character ==
== The Player Character ==
Line 9: Line 7:
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".
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.
We would like to place the player on 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;">
Line 20: Line 18:


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


Line 41: Line 39:
</div>
</div>


== Preparing the game turn engine ==


== 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, let's just alternate their turns evenly. But even in this simple case, we can use the <code>ROT.Engine</code> timing framework to our advantage.


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? First, the <code>ROT.Scheduler.Simple</code> will be fed with all available ''actors'' - this component will take care about fair turn scheduling. The <code>ROT.Engine</code> will then use this scheduler to automatically call relevant actors in a loop. (Note: we pass <code>true</code> as a second argument to <code>scheduler.add</code> - this means that our actor is not a one-shot event, but rather a recurring item.)


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.
It is very important to embrace the fact that everything is asynchronous in the world of client-side JavaScript: there are basically no blocking calls. This eliminates the possibility of having a simple ''while'' loop as our main timing/scheduling instrument. Fortunately, the <code>ROT.Engine</code> is well prepared for this.


Creating the engine is just a matter of adding a few lines to our code:  
Creating the scheduler and 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;">
Line 55: Line 54:


Game.init = function() {
Game.init = function() {
     this.engine = new ROT.Engine();
     var scheduler = new ROT.Scheduler.Simple();
     this.engine.addActor(this.player);
    scheduler.add(this.player, true);
     this.engine();
     this.engine = new ROT.Engine(scheduler);
     this.engine.start();
}
}
</syntaxhighlight>
</syntaxhighlight>
</div>
</div>


== Console output: ROT.Display ==
== Interaction between actors and the engine ==
 
There is a tight symbiotic relationship between the engine and its actors. When running, the engine repeatedly picks a proper actor (using the scheduler) and calls the actor's <code>act()</code> method. Actors are allowed to interrupt this loop (when waiting asynchronously, for example) by calling <code>ROT.Engine::lock</code> and resume it (<code>ROT.Engine::unlock</code>).
 
It is possible to have multiple lock levels (the lock is recursive); this allows for complex chaining of asynchronous calls. Fortunately, this won't be needed in our simple game.


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.
So, what is an actor? Any JS object with the '''<code>act</code>''' method.


<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 = {
Player.prototype.act = function() {
     display: null,
     Game.engine.lock();
    /* wait for user input; do stuff when user hits a key */
    window.addEventListener("keydown", this);
}


    init: function() {
Player.prototype.handleEvent = function(e) {
        this.display = new ROT.Display();
     /* process user input */
        document.body.appendChild(this.display.getContainer());
     }
}
}
</syntaxhighlight>
</syntaxhighlight>
</div>
</div>


Note that this console has a default size of 80x25 cells; if we wanted different default dimensions, we would configure them via <code>ROT.DEFAULT_WIDTH</code> and <code>ROT.DEFAULT_HEIGHT</code>.
We are using somewhat uncommon (but very useful!) technique of assigning event handlers: we pass a JS object as a second argument to the <code>addEventListener</code> call. Such object (<code>this</code>, in this case) must have the <code>handleEvent</code> method, which will be called once the event ("keydown") occurs.
 
== Working with the keyboard and moving the player around ==
 
There is one last bit remaining to implement: detect the pressed key, decide whether it is valid and move the player accordingly.
 
Our event handler (<code>handleEvent</code>) gets executed with one argument: the Event object. Its <code>keyCode</code> property is a number code of the key being pressed. Let's create a mapping of allowed key codes (this code sample uses numpad keys, but it is trivial to extend it to other layouts as well):


== Generating a dungeon map ==
<div style="padding:5px; background-color:#eee; margin-bottom:2em;">
<syntaxhighlight lang="javascript">
var keyMap = {};
keyMap[38] = 0;
keyMap[33] = 1;
keyMap[39] = 2;
keyMap[34] = 3;
keyMap[40] = 4;
keyMap[35] = 5;
keyMap[37] = 6;
keyMap[36] = 7;
</syntaxhighlight>
</div>


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.
Numeric values are not chosen randomly: they correspond to directional constants in <code>rot.js</code> (8-topology, clockwise, starting at the top - the same as CSS does).


This might be a good time to check out the [http://ondras.github.com/rot.js/manual/ rot.js manual], which contains useful code samples and usage overview.
We need to perform a two-step validation of user input:


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.
# If the key code is not present in <code>keyMap</code>, the user pressed a key which we cannot handle
# If the key code '''is''' present, we need to check whether the PC can move in that direction


'''NOTE:''' We are passing <code>digCallback.bind(this)</code> instead of just <code>digCallback</code> to the Digger. This is necessary to ensure that our callback is called within a correct context (''activation object'' in ECMA parlance).
To convert a directional constant (0..7) to a map coordinates, we can use the <code>ROT.DIRS</code> set of topological diffs:


<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">
Game.map = {};
Player.prototype.handleEvent = function(e) {
Game._generateMap = function() {
     var keyMap = {};
     var digger = new ROT.Map.Digger();
    keyMap[38] = 0;
    keyMap[33] = 1;
    keyMap[39] = 2;
    keyMap[34] = 3;
    keyMap[40] = 4;
    keyMap[35] = 5;
    keyMap[37] = 6;
    keyMap[36] = 7;


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


        var key = x+","+y;
     if (!(code in keyMap)) { return; }
        this.map[key] = "·";
    }
     digger.create(digCallback.bind(this));
}
</syntaxhighlight>
</div>


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.
    var diff = ROT.DIRS[8][keyMap[code]];
    var newX = this._x + diff[0];
    var newY = this._y + diff[1];


<div style="padding:5px; background-color:#eee; margin-bottom:2em;">
     var newKey = newX + "," + newY;
<syntaxhighlight lang="javascript">
    if (!(newKey in Game.map)) { return; } /* cannot move in this direction */
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]);
    }
}
}
</syntaxhighlight>
</syntaxhighlight>
</div>
</div>


== Randomly generated boxes ==
The actual move is performed in two steps - redrawing the old position and redrawing the new position. After that, we remove our keyboard listener (the turn has ended!) and - '''importantly''' - resume the game engine (<code>unlock()</code>).
 
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 [[RNG|Random number generator]].
 
<code>ROT.RNG</code> 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 <code>Math.random</code> does. The proper way of doing this is calling <code>ROT.RNG.getUniform()</code>.
 
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.


<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">
Game._generateMap = function() {
Player.prototype.handleEvent = function(e) {
     var digger = new ROT.Map.Digger();
     /* ...previous stuff... */
    var freeCells = [];


     var digCallback = function(x, y, value) {
     Game.display.draw(this._x, this._y, Game.map[this._x+","+this._y]);
        if (value) { return; } /* do not store walls */
     this._x = newX;
 
     this._y = newY;
        freeCells.push(key);
     this._draw();
        var key = x+","+y;
    window.removeEventListener("keydown", this);
        this.map[key] = "·";
     Game.engine.unlock();
     }
}
    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] = "*";
    }
};
</syntaxhighlight>
</syntaxhighlight>
</div>
</div>


And that's all for part 2. The whole working code is available at [http://jsfiddle.net/rotjs/CZ8YJ/ jsfiddle.net]. Feel free to continue in [[Rot.js tutorial, part 3]].


And that's all for part 2. The whole working code is available at [http://jsfiddle.net/rotjs/CZ8YJ/ jsfiddle.net].
[[Category:Developing]]

Latest revision as of 20:33, 17 June 2017

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

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 on 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, "@", "#ff0");
}

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, let's just alternate their turns evenly. But even in this simple case, we can use the ROT.Engine timing framework to our advantage.

How does this work? First, the ROT.Scheduler.Simple will be fed with all available actors - this component will take care about fair turn scheduling. The ROT.Engine will then use this scheduler to automatically call relevant actors in a loop. (Note: we pass true as a second argument to scheduler.add - this means that our actor is not a one-shot event, but rather a recurring item.)

It is very important to embrace the fact that everything is asynchronous in the world of client-side JavaScript: there are basically no blocking calls. This eliminates the possibility of having a simple while loop as our main timing/scheduling instrument. Fortunately, the ROT.Engine is well prepared for this.

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

Game.engine = null;

Game.init = function() {
    var scheduler = new ROT.Scheduler.Simple();
    scheduler.add(this.player, true);
    this.engine = new ROT.Engine(scheduler);
    this.engine.start();
}

Interaction between actors and the engine

There is a tight symbiotic relationship between the engine and its actors. When running, the engine repeatedly picks a proper actor (using the scheduler) and calls the actor's act() method. Actors are allowed to interrupt this loop (when waiting asynchronously, for example) by calling ROT.Engine::lock and resume it (ROT.Engine::unlock).

It is possible to have multiple lock levels (the lock is recursive); this allows for complex chaining of asynchronous calls. Fortunately, this won't be needed in our simple game.

So, what is an actor? Any JS object with the act method.

Player.prototype.act = function() {
    Game.engine.lock();
    /* wait for user input; do stuff when user hits a key */
    window.addEventListener("keydown", this);
}

Player.prototype.handleEvent = function(e) {
    /* process user input */
}

We are using somewhat uncommon (but very useful!) technique of assigning event handlers: we pass a JS object as a second argument to the addEventListener call. Such object (this, in this case) must have the handleEvent method, which will be called once the event ("keydown") occurs.

Working with the keyboard and moving the player around

There is one last bit remaining to implement: detect the pressed key, decide whether it is valid and move the player accordingly.

Our event handler (handleEvent) gets executed with one argument: the Event object. Its keyCode property is a number code of the key being pressed. Let's create a mapping of allowed key codes (this code sample uses numpad keys, but it is trivial to extend it to other layouts as well):

var keyMap = {};
keyMap[38] = 0;
keyMap[33] = 1;
keyMap[39] = 2;
keyMap[34] = 3;
keyMap[40] = 4;
keyMap[35] = 5;
keyMap[37] = 6;
keyMap[36] = 7;

Numeric values are not chosen randomly: they correspond to directional constants in rot.js (8-topology, clockwise, starting at the top - the same as CSS does).

We need to perform a two-step validation of user input:

  1. If the key code is not present in keyMap, the user pressed a key which we cannot handle
  2. If the key code is present, we need to check whether the PC can move in that direction

To convert a directional constant (0..7) to a map coordinates, we can use the ROT.DIRS set of topological diffs:

Player.prototype.handleEvent = function(e) {
    var keyMap = {};
    keyMap[38] = 0;
    keyMap[33] = 1;
    keyMap[39] = 2;
    keyMap[34] = 3;
    keyMap[40] = 4;
    keyMap[35] = 5;
    keyMap[37] = 6;
    keyMap[36] = 7;

    var code = e.keyCode;

    if (!(code in keyMap)) { return; }

    var diff = ROT.DIRS[8][keyMap[code]];
    var newX = this._x + diff[0];
    var newY = this._y + diff[1];

    var newKey = newX + "," + newY;
    if (!(newKey in Game.map)) { return; } /* cannot move in this direction */
}

The actual move is performed in two steps - redrawing the old position and redrawing the new position. After that, we remove our keyboard listener (the turn has ended!) and - importantly - resume the game engine (unlock()).

Player.prototype.handleEvent = function(e) {
    /* ...previous stuff... */

    Game.display.draw(this._x, this._y, Game.map[this._x+","+this._y]);
    this._x = newX;
    this._y = newY;
    this._draw();
    window.removeEventListener("keydown", this);
    Game.engine.unlock();
}

And that's all for part 2. The whole working code is available at jsfiddle.net. Feel free to continue in Rot.js tutorial, part 3.