Friday, May 21, 2010

Shadows in Raphaël.js

‹prev | My Chain | next›

Last night I made a bit of a mess out of animating my players and labels as they move about the room in my (fab) game. It works:



But it is done by independently animating the label and the player. The label is offset by 10 pixels, but everything else about the label is duplicated in the Player. I have to stop both the Player and the label the same way, I have to animate both the same way, and I have to initially draw both the same way. That's a lot of duplication.

So let's try it another way. Instead of animating the label as an independent object, I will hook it into the Player animation via raphaël.js's onAnimation callback:
Player.prototype.attach_drawable = function(drawable) {
this.drawable = drawable;
var label = drawable.paper.text(this.x, this.y + 10, this.id);
this.label = label;

drawable.onAnimation(function(){
label.attr({x: drawable.attr("cx"), y: drawable.attr("cy") + 10});
});

};
I can then eliminate all other references to label in the code because this callback will draw the label in a new position each increment of the Player (or the drawable representation of it) along its path about the room.

Nice!

The only difficulty I had was choosing the "right" X and Y. I know from playing about with raphaël.js over the past week that cx and cy are the center of my player avatar in the room, so it only make sense to use them when moving calculating where to put the label.

What I could not figure out was how to set the location of the label. I initially tried cx and cy for that as well, but it had no effect. The label stayed in the start position as the Player moved about the room. I had expected x/y to start the label at that position and then draw the label to the right of center, but, in the end, it does exactly what I had hoped for:



Up next: more fab.js as I get chatting underway.

Day #110

Thursday, May 20, 2010

Moving Sets in Raphaël.js

‹prev | My Chain | next›

Things are going fairly well with my (fab) game. My fab.js backend is doing most of what I need it to (keeping track of players, dropping idle players). My frontend is working fairly well in raphaël.js as well. Tonight, I would like to see if I can attached a name to players in the game room (right now, they are just dots).

Raphaël's set() seems like a good option. Currently, the Room is drawing the player with Raphaël's circle() and returning that to be moved as the Player moves about the room:
Room.prototype.draw_player = function(player, color) {
var c = this.paper.circle(player.y, player.x, 3);
c.attr({fill: color, opacity: 0.5});
return c;
};
The set() method groups elements together. So let's try grouping this circle with a text element just below it:
Room.prototype.draw_player = function(player, color) {
var st = this.paper.set();
st.push(
this.paper.circle(player.x, player.y, 3),
this.paper.text(player.x, player.y + 10, player.id)
);
st.attr({fill: color, opacity: 0.5});

return st;
};
Trying that out in the browser it works!:



It works... but only up to a point. When I try to move this set with the same animateAlong() method, nothing happens. Digging through the raphaël.js source code a bit, it seems that only animate() was implemented for sets. I would hazard a guess that it is difficult to animate a bunch of arbitrary objects along a path, which is why this is not part of raphaël.js yet. Still I really would like this feature.

For now, I am going to fall back on a terrible hack. Hopefully I can come up with something better in the future, but...

I revert my set code. Instead, when the Player is handed its "drawable" circle() I add a second object 10 pixels below (y-pixels increase down the page):
Player.prototype.attach_drawable = function(drawable) {
this.drawable = drawable;
this.label = drawable.paper.text(this.x, this.y + 10, this.id);
};
Here, I am using the paper attribute that the cirle() drawable (and any raphaël.js element) has.

With a label now an attribute on Player, I need to animate the label along a path 10 pixels below the path the Player walks:
Player.prototype.walk_to = function(x, y) {
var p = "M"+ this.x + " " + this.y +
"L" + x + " " + y;
this.drawable.animateAlong(p, 3000);

var pl = "M"+ this.x + " " + this.y + 10 +
"L" + x + " " + y + 10;
this.label.animateAlong(p, 3000);


this.x = x;
this.y = y;
};
And, when the Player stops, I need to stop the label as well:
Player.prototype.stop = function () {
this.drawable.stop();
this.label.stop();
this.x = this.drawable.attrs.cx;
this.y = this.drawable.attrs.cy;
};
I am not at all satisfied with this solution but it does work:



I will stop there for the night and ruminate on how I might do this better tomorrow. Maybe onAnimation()?

Day #109

Wednesday, May 19, 2010

From Raphaël.js to Fab.js: A Tale of One Player's Journey

‹prev | My Chain | next›

Up tonight, I want to kick players out of my (fab) game. I am not trying to drop unruly players, just unresponsive players.

I start with the client code. When a Player quits, I need to remove the raphaël.js drawable object:
Player.prototype.quit = function() {
this.drawable.remove();
}
("drawable" refers to a raphaël.js circle and remove() is a raphaël.js method).

For good measure, I delete the attributes from the player object:
Player.prototype.quit = function() {
this.drawable.remove();
delete this.x;
delete this.y;
delete this.id;

}
I am not trying to save memory or anything of the sort. I remove these attributes so that the Player no longer quacks like a Player. If anything tries to treat it as such, errors will happen.

Now that a Player can quit a room, I need to expose an interface for fab.js to be able to communicate with browsers to inform them of a departure. The interface for this is the PlayerList in the browser. The PlayerList holds the current player (me) as well as all the other current players. I will handle removing these other players first:
PlayerList.prototype.remove_player = function(id) {
this.get_player(id).quit();
delete this.other_players[id];
};
Actually, that is quite easy. I call the quit() method that I just defined on the Player leaving the room. Then I delete the player from the player list.

If the player quitting the room is me (e.g. I have been idle too long), then I need to quit the room as do all other players. From my perspective, if I leave, I no longer care about the other players. So:
PlayerList.prototype.remove_player = function(id) {
if (this.me.id == id) {
// I am leaving and so is everyone else (as far as I'm concerned)
this.me.quit();
for (var oid in this.other_players) {
this.other_players[oid].quit();
}
}

else {
this.get_player(id).quit();
delete this.other_players[id];
}
};
With that, I am ready to get started in the fab.js backend. First up, I do a little refactoring of the code so that the comet communication method is a bit more general. It had been specific to walking players in the rooms of each client. Now the broadcast() function can send any command to the PlayerList in the connected browsers:
function broadcast(comet_command) {
var num = 0;
for (var id in players) {
var player = players[id];
player.listener({body: comet_command});
num++;
}
puts("broadcasting to "+num+" players");
}
It can send any command, such as the new remove_player() method. To get started with timing out players, I add a simple setTimeout() immediately after a player is added in fab.js:
// ...
puts("adding: " + obj.body.id);
players[obj.body.id] = {status: obj.body, listener: out};

setTimeout(function() {
drop_player(obj.body.id);
}, 5000);


broadcast(comet_walk_player(JSON.stringify(obj.body)));
...
With that, 5 seconds after connecting, the drop_player() method will be called which, in turn, broadcasts to all connected clients that said player should be removed:
function drop_player(id) {
puts("Dropping player \""+ id +"\"");
broadcast(comet_quit_player(id));
}

function comet_quit_player(id) {
return comet_wrap('player_list.remove_player("'+ id +'")');
}
Trying this out, and after moving the player "bob" about the room, I am dropped:
cstrom@whitefall:~/repos/my_fab_game$ node game.js
adding: bob
broadcasting to 1 players
broadcasting to 1 players
updating player status: bob
Dropping player "bob"
broadcasting to 1 players
The last step is to move this into per-player idle watching inside the fab.js. In the idle_watch() function, I clear any existing timeout, then set a new one. If 60 seconds pass, then the Player will be removed:
function idle_watch(id) {
if (players[id].idle_timeout) {
clearTimeout(players[id].idle_timeout);
}

players[id].idle_timeout = setTimeout(function() {
drop_player(id);
}, 60*1000);
}
Calling this method anytime a player updates its status will ensure that active players remain in the room as long as they like:
function update_player_status(status) {
puts("updating player status: " + status.id);
players[status.id].status = status;
idle_watch(status.id);
}
That is a good stopping point for tonight. Up tomorrow, more raphaël.js work, I think. I would like to include player names next to the player icons. Then it'll be onto the next killer feature (in my son's eyes): chatting.

Day #108

Tuesday, May 18, 2010

Retrospective: Week Fourteen

‹prev | My Chain | next›

In an ongoing effort to make this chain as valuable as possible to myself (and possibly others), I perform a weekly retrospective of how the past week went (notes from last week). I do this on Tuesdays to avoid conflicts with B'more on Rails, which usually holds events then.

This week (like the week before), I continue working on my (fab) game—a game inspired by the fab.js framework that I am writing for my kids.

WHAT WENT WELL

  • I played tag with my son in my (fab) game. I was quite excited to have gotten the game to this point already.
  • Figured out how to broadcast to many fab.js clients
  • Started playing with raphaël.js
    • Very nice / easy to pick up framework.
    • Needed to reach under the API covers (to stop animation). That's something of a not-so-well, but the Raphaël code is so well organized that it was easy to accomplish what I wanted.
  • Refactored a fab.js unary into a binary with relative ease, using that to support a backend player list. The code was prettier as well!

OBSTACLES / THINGS THAT WENT NOT SO WELL

  • Still not testing my javascript.
  • Had not separated my Room/Player concerns as well as I hoped. Switching from <canvas> to Raphaël forced changes such that the Room, which had been watching the Player move, now moves the Player and informs the Player where it is. This required a fair number of changes in my code. I wonder if it possible to have coded this such that fewer changes were required—less coupling between the two would be a good thing.
  • I struggled with setting the comet iframe's src more than I should have. I was sure that I needed to muck with the window.location inside the iframe. It took me much longer than it should have to figure out that I could simply set the src attribute directly.

WHAT I'LL TRY NEXT WEEK

  • I am having way too much fun playing around with these Javascript frameworks. That is certainly a good thing, but I do ultimately want to produce robust, accurate, maintainable code. That means testing. I must test!
  • I am not sure if it is possible to detect disconnecting clients in fab.js. Worth some time to investigate.
  • Regardless of the answer to the above, I ought to be able to add client heartbeats to passively remove players from the room.


Day #107

Monday, May 17, 2010

Stopping Animation in Raphaël.js

‹prev | My Chain | next›

Last night I was able to get animation with raphaël.js working in my (fab) game. Tonight I want to stop it.

More to the point, I want to stop the animation of my player walking the room when I click somewhere else in the room. If I am already half way to my destination when I click, I want the animation to halt immediately. The player should then move from that location to the click event. Currently that is not happening:



I had already gotten this working with my low-level<canvas> code. I even have a method on Player that stops the walk before restarting to a new destination. In the new raphaël.js branch, it is not doing much:
Player.prototype.stop = function () {
console.debug("try to stop()");
};
That seems like a good place to get started. First up, I think I will try stop(), an undocumented raphaël.js method that halts animations:
Player.prototype.stop = function () {
console.debug("try to stop()");
this.drawable.stop();
};
Recall that drawable is how Player remembers the raphaël element (circle in this case).

That seems to halt the animation, but it is hard to know for sure. A second click event starts the animation right back up starting from the wrong coordinates. Recall also that the walk_to method sets the coordinates of a Player to the destination:
Player.prototype.walk_to = function(x, y) {
var self = this;
var p = "M"+ this.x + " " + this.y +
"L" + x + " " + y;
this.drawable.animateAlong(p, 3000);
this.x = x;
this.y = y;

};
In the case of the second click before the Player reaches the destination, those coordinates are wrong, messing up the next walk_to. What I need is a way to know the location on the raphaël.js element when the animation is stopped. Since I am already reaching under the raphaël.js API, I will go just a bit further to access the center-x / center-y attribute of my drawable element:
 Player.prototype.stop = function () {
console.debug("try to stop()");
this.drawable.stop();
this.x = this.drawable.attrs.cx;
this.y = this.drawable.attrs.cy;

};
I could have used the getBBox method as well, but then I would have to calculate the center-x / center-y value. Why bother when I can reach into attrs for it? True, there is something to be said for staying within the exposed API, but I have already given up on that when I called stop in the first place.

With that, my raphaël.js room can now animate movement even when I change my mind mid-walk:



Up tomorrow, it is retrospective time. Then I need to make sure that my raphaël-based frontend is still talking nicely to my fab.js backend.

Day #106

Sunday, May 16, 2010

Animating with Raphaël.js

‹prev | My Chain | next›

Tonight, I continue my exploration of raphaël.js. Last night, I was able to get the basic canvas in place and hook in an event listener into my (fab) game. At that point, I realized that it was going to require some refactoring of the player animation to work with raphaël.js. Now I start that refactoring.

The difference between my <canvas> based animation and the way that raphaël animates is that my <canvas> code only watches/reports as the player itself moves. Raphaël's animateAlong() moves items about on its "paper", then reports on locations. I had hoped my code would prove decoupled enough that I could change only the Room or only the Player. Sadly, both will require changes.

First up, I re-arrange the player list and room so that player list knows about the room, not the other way around:
    var room = new Room($("#room-container")[0]);
player_list = new PlayerList(me, room);
The room no longer needs to watch the players—now the players will have to watch what happens in the room. After updating the constructors of each, I provide a means for the player list to tell each Player about the raphaël.js drawing element:
Player.prototype.attach_drawable = function(drawable) {
this.drawable = drawable;
};
This "drawable" element in the room comes from the circle object drawn by the Room:
Room.prototype.draw_player = function(player, color) {
var c = this.paper.circle(player.y, player.x, 3);
c.attr({fill: color, opacity: 0.5});
return c;
};
(It is the player list's job to attach the two).

With that, I can call the raphaël.js animateAlong() method with an SVG path element to animate the motion of the player in the room:
Player.prototype.walk_to = function(x, y) {
var self = this;
var p = "M"+ this.x + " " + this.y +
"L" + x + " " + y;
this.drawable.animateAlong(p, 3000)
};
With that, I can actually animate my players again:



Nice! That was a bit easier than working with <canvas> (which probably helped overcoming some problems I might have encountered). Unfortunately, I do run into one of the problems I had already solved in my <canvas> code—clicking a new destination before the animation has completed fouls up the walk (animations combine).

I am unsure if that can be resolved easily in raphaël.js. I will investigate tomorrow.

Day #105

Saturday, May 15, 2010

Getting Started with Raphaël.js

‹prev | My Chain | next›

Tonight, I will explore drawing my game with the raphaël.js javascript framework. I have no interest in cross-browser support (Webkit and Firefox are sufficient), but I would like to see if drawing things are easier with it and maybe a little less CPU intensive.

So I remove my <canvas> tag, replacing it with a container for my raphaël.js canvas:
   <div id="room-container"></div>
...and pass this into my Room constructor:
    new Room($("#room-container")[0], player_list);
After updating my constructor to expect the container rather than a <canvas> element, my draw routine starts in with the raphaël.js:
Room.prototype.draw = function() {

this.paper = Raphael(this.container, 500, 500);
this.paper.clear();
this.paper.rect(0, 0, 500, 500, 10).attr({fill: "#fff", stroke: "none"});

// calls to draw the players
}
This initializes a raphaël element, clears it, then fills it in with white. Simple enough. Drawing players with raphaël is also fairly straight forward:
Room.prototype.draw_player = function(player, color) {
var c = this.paper.circle(player.y, player.x, 3);
c.attr({fill: color, opacity: 0.5});
};
I just borrow some of the sample code from the very excellent documentation for drawing circles. I now have a nicely rendered room with very little effort:



Unfortunately, now I run into problems. I move players about by clicking on the room and having them follow the click. The problem here is trying to figure out where to attach that click event. When I was using a straight <canvas> element, I could attach my click handler directly to it. That does not work with raphaël, nor can I attach the handler to the "paper"'s node.

In the end I am forced to attach the handler to the containing <div>:
Room.prototype.init_events = function() {
var self = this;
$(this.container).click(function(evt) {
var decorated_event = self.decorate_event(evt);
self.subscribers.forEach(
function(subscriber) { subscriber.notify(decorated_event); }
);
});
};
Although the event is not listening on the real target, it seems to be close enough. My player is again notified of the event and sends movement information to the fab.js backend once more.

I stop here for the night. Tomorrow I will pick back up with animating my players inside raphaël. That seem relatively easy to do, but it will require a fair bit of rejiggering of responsibilities in my code so far.

Day #104