Tag Archives: javascript

CraftJS; interesting potential

The other month/week I resumed some dabbling/hacking experiments in working with HTML5’s canvas. This go around, I decided to give CraftyJS a try.

The short version of my experiments, CraftyJS has a lot of potential if it can get it’s memory leaks under control, which might be a daunting task.

Here’s the example Pong game implementation that can be found on CraftyJS’s website:

 
Crafty.init(600,300);
Crafty.background("rgb(127,127,127)");
 
//Paddles
Crafty.e("Paddle, 2D, DOM, Color, Multiway")
    .color('rgb(255,0,0)')
    .attr({ x: 20, y: 100, w: 10, h: 100 })
    .multiway(4, { W: -90, S: 90 });
 
Crafty.e("Paddle, 2D, DOM, Color, Multiway")
    .color('rgb(0,255,0)')
    .attr({ x: 580, y: 100, w: 10, h: 100 })
    .multiway(4, { UP_ARROW: -90, DOWN_ARROW: 90 });
 
//Ball
Crafty.e("2D, DOM, Color, Collision")
    .color('rgb(0,0,255)')
    .attr({ x: 300, y: 150, w: 10, h: 10,
            dX: Crafty.math.randomInt(2, 5),
            dY: Crafty.math.randomInt(2, 5) })
    .bind('EnterFrame', function () {
        //hit floor or roof
        if (this.y <= 0 || this.y >= 290)
            this.dY *= -1;
 
        if (this.x > 600) {
            this.x = 300;
            Crafty("LeftPoints").each(function () {
                this.text(++this.points + " Points") });
        }
        if (this.x < 10) {
            this.x = 300;
            Crafty("RightPoints").each(function () {
                this.text(++this.points + " Points") });
        }
 
        this.x += this.dX;
        this.y += this.dY;
    })
    .onHit('Paddle', function () {
    this.dX *= -1;
})
 
//Score boards
Crafty.e("LeftPoints, DOM, 2D, Text")
    .attr({ x: 20, y: 20, w: 100, h: 20, points: 0 })
    .text("0 Points");
Crafty.e("RightPoints, DOM, 2D, Text")
    .attr({ x: 515, y: 20, w: 100, h: 20, points: 0 })
    .text("0 Points");

Now I will break this down.

Crafty.init(600,300);
Crafty.background("rgb(127,127,127)");

Relatively straight forward; this generates a HTML5 canvas element of 600×300 pixels, sets the color to a neutral color range.

Crafty.e("Paddle, 2D, DOM, Color, Multiway")
    .color('rgb(255,0,0)')
    .attr({ x: 20, y: 100, w: 10, h: 100 })
    .multiway(4, { W: -90, S: 90 });

Part of Crafty’s cleverness is in it’s component based entity system. The first line tells the Crafty library that you’re defining a new entity called “Paddle” which is a 2D, DOM behavior like, color’d objected that reacts to multiple user inputs. Break down:

.color(…) defines the paddles color
.attr(…) defines the entities dimensions AND position.
.multiway(…) is a clear API method which states
the entities movement speed, and then which direction a triggered keyboard input will send the entitiy. So in the above case W is north, and S is south.

Skipping the other paddle, we come to the ball in a pong game.

Crafty.e("2D, DOM, Color, Collision")
    .color('rgb(0,0,255)')
    .attr({ x: 300, y: 150, w: 10, h: 10,
            dX: Crafty.math.randomInt(2, 5),
            dY: Crafty.math.randomInt(2, 5) })
    .bind('EnterFrame', function () {
        //hit floor or roof
        if (this.y <= 0 || this.y >= 290)
            this.dY *= -1;
 
        if (this.x > 600) {
            this.x = 300;
            Crafty("LeftPoints").each(function () {
                this.text(++this.points + " Points") });
        }
        if (this.x < 10) {
            this.x = 300;
            Crafty("RightPoints").each(function () {
                this.text(++this.points + " Points") });
        }
 
        this.x += this.dX;
        this.y += this.dY;
    })
    .onHit('Paddle', function () {
    this.dX *= -1;
})

Something I glossed over, Crafty’s e(…) function is actually a Javascript prototype class generator. It’s important to note that because of the interplay between .attr() and every other post e(…) method call.

In the above

.attr({ x: 300, y: 150, w: 10, h: 10,
            dX: Crafty.math.randomInt(2, 5),
            dY: Crafty.math.randomInt(2, 5) })

defines additional properties of the entity. x/y & w/h are already used by the 2D and DOM components to determine the entities position on but in the later .bind(“EnterFrame”) notice that the logic involved is referencing this attributes.

So inside the EnterFrame handler for the Ball are two crucial sections.

if (this.x > 600) {
            this.x = 300;
            Crafty("LeftPoints").each(function () {
                this.text(++this.points + " Points") });
        }
        if (this.x < 10) {
            this.x = 300;
            Crafty("RightPoints").each(function () {
                this.text(++this.points + " Points") });
        }
<pre>
 
These two if clauses handle bounds check's and then depending on position award the appropriate side a point.
 
Notice the Crafty("") calls.  In this case Crafty("LeftPoints") calls up the appropriate entity or entities ( in this case there are only 1 per side ) and applies a closure to increment the winning side's this.points and body text.
 
 
The other crucial section is the 2 line closure 
 
<pre lang="javascript">
.onHit('Paddle', function () {
    this.dX *= -1;
}

A fairly cool concept in Crafty is that collision detection between almost any entity is dealt with by Crafty, so to determine if the Ball hits a paddle, you just have to ask Crafty.

Summary

I was fairly impressed with CraftyJS, it is very much the spiritual relative of jQuery for a dirt simple and comfortably clever API. Unfortunately Crafty can blind side you with it’s cleverness if you’re not careful. What I mean is that in experimenting with CraftyJS I found it fairly easy to create non-obvious memory leaks and or abuse closures to much.

Still it’s a fairly nice library and though this post is slightly long, I am only covering a thin scratch of the depth that is in CraftJS. This could be a fantastic building stage for making a slew of quick and dirty games.

A web-console implemented in nodeJS

Reading over this ( http://gonzalo123.wordpress.com/2011/05/16/web-console-with-node-js/ ) , I felt this was a pretty good and relatively real world example of nodeJS’s capabilities. I did find one line near the end very poignant and reflective of my own opinions at the end of the show & tell post

I don’t know if node.js is the future or is just another hype, but it’s easy. And cool. Really cool.

New language to the toolset: NodeJS

I’ve started self-teaching myself NodeJS and not surprisingly there was a recent popular reddit link pointing to a not very short introduction to nodejs here ( http://anders.janmyr.com/2011/05/not-very-short-introduction-to-nodejs.html ) . At this point I haven’t found any good books for reference lookup… but hopefully in a week or so I’ll have gotten spooled up enough to be able to report back.

In the meantime as I use Ubuntu for everything but games, this short article here ( http://www.codediesel.com/linux/installing-node-js-on-ubuntu-10-04/ ) was enough to get a working environment running though I recommend using a pristine virtual machine instance to keep things simple.

Last point, a reliable friend & peer of mine recommended I check out this MVC like framework for NodeJS ( http://expressjs.com/ ). Preliminary it feels like a hybrid between Twistd and CherryPy in Python or Limonade PHP as far as style… aiming more for simplicity over feature/complexity.

JQuery dataTable plugin quick notes

Server-side processing

To return the names of the columns you want, you need to use aoColumndefs and provided individual objects with the property sName.

Below is most of the implementation for a jeditable Ajax driven dataTables, this is the Alpha version and still needs a lot of love in places, but the gist of it is here

var semesterTable = $("#semesterViewTable").dataTable({
                "bProcessing"   : true
            ,   "bServerSide"   : true
            ,   "sAjaxSource"   : "<?php echo url_for("roster/ajax/{$semester_id}"); ?>"
            ,   "fnRowCallback" : function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
                                    //console.log(nRow, aData, iDisplayIndex, iDisplayIndexFull);
                                    var recordId = aData[0];
                                    $("td", nRow).data("recordId", recordId);
                                    return nRow;
                                }
            , "fnDrawCallback"  : function(){
                                    $("td.editableMajor")
                                        .editable("<?php echo url_for("roster/edit_record");?>",
                                                    {                                                        
                                                          loadurl: "<?php echo url_for("roster/distinct/major/{$semester_id}") ?>"
                                                        , type: "select"
                                                        , submit: "OK"
                                                        , method: "post"
                                                        , submitdata: function(){
                                                            console.log(this, arguments);
                                                            var $this = $(this);
                                                            return {
                                                                    recordId: $this.data("recordId")
                                                                    , classes: $this.attr("class")
                                                                }
                                                        }
                                                    });
 
                                }
            /* Seriously a meta-generator for this would be nice */
            ,"aoColumnDefs": [
                ,{ sName:"record_id",          aTargets:[00], bSearchable:false, bVisible:false }
                ,{ sName:"roster_date",         aTargets:[01], sClass:"roster_date"}
                ,{ sName:"roster_name_both",    aTargets:[02], sClass:"roster_name_both"}
                ,{ sName:"roster_student_id",   aTargets:[03], sClass:"roster_student_id"}
                ,{ sName:"roster_major1",       aTargets:[04], sClass:"roster_major1 editableMajor"}
                ,{ sName:"roster_major2",       aTargets:[05], sClass:"roster_major2 editableMajor"}
                ,{ sName:"roster_major3",       aTargets:[06], sClass:"roster_major3 editableMajor"}
                ,{ sName:"roster_major4",       aTargets:[07], sClass:"roster_major4 editableMajor"}
                ,{ sName:"roster_minor1",       aTargets:[08], sClass:"roster_minor1 editableMajor"}
                ,{ sName:"roster_minor2",       aTargets:[09], sClass:"roster_minor2 editableMajor"}
            ]
    });

For the tbody, just put something like

        <tbody><tr><td>Chill the fuck out, it's loading</td></tr></tbody>

Server side data contract

dataTables expects a JSON’ified construct like this

$responseBody = array(
		"sEcho" => intval($input['sEcho']),
		"iTotalRecords" => (int) $count,
		"iTotalDisplayRecords" => count($data),
		"aaData" => $data
            );
  • sEcho is a security variable used by dataTables, basically just send it back and don’t worry about it
  • iTotalRecords – is the MAXIMUM # of records in the data set without any filtering
  • iTotalDisplayRecords – is the MAXIMUM # of records in the data set WITH filtering
  • An array of numerically indexed arrays, dataTables doesn’t like associative arrays

Total and Display total records

If the blink tag still worked reliably, I’d put a neon sign here. Basically you need to do 3 queries per Ajax call… call 1 is to get a

 
   SELECT count(1) FROM sourceTABLE

call 2 is

 SELECT count(1) FROM sourceTable WHERE someCriteria 

and finally call 3 is

 SELECT yourColumnList FROM sourceTable WHERE someCriteria

With memcache or such, I’d advise caching the total count but no matter what you unfortunately need to make these three SQL calls :(.

Snake game prototype

Running live here

User input is fed off the left & right cursor keys.

Ping additions included a formalized Quad tree library into the ping.Lib namespace but I want to fix up the factory function I wrote to take an instance of the Canvas rendering class instead of manually writing out the root dimensions. Otherwise collision checks are still a tad wonky… there’s a high propensity for near misses unfortunately 🙁

Canvas pixel collision detection

So… a fair number of people arrive here looking for how to detect when a pixel/object/thing has collided with something else.

I’ll add more information in the future but in the interim, the quick and dirty advice I can provide:

Given p = x, y where this is the point your trying to determine if it intersects another… the best place is to start with bounding box logic.  Regardless of what shape your object is, if wrap it in an invisible box boundry, it’s relatively trivial to do:

box upper left origin is bX, bY off size sizeX, sizeY.   If p.x greater then bX and p.x less then bX + sizeX AND p.y greater then bY and p.y less then bY + sizeY   you’re inside the bounding box and it’s highly likely your point has or will soon be colliding with an object.

That’s pretty much it and is perfect if you don’t mine lagging the crap out of whatever is running this logic.    To make these collision checks performant, you need to make the computer do less work.   For two dimensional space, my personnel research has led me to the Quad tree structure ( wikipedia article ).  I’ve got a brute force / naive implementation prototyped  @ here & here but as of 2011 March 9th it is not finished and needs some more work.

Basically Quad tree’s provides a super quick way for you to determine if there is any other objects in relative space to an entity.  Doing a quick lookup, if there’s nothing nearby then you can skip the bounding box checks and then the stupidly expensive perimeter intersection checks.

Full library is here and like most of my pet projects is heavily undocumented and completely absent of unit-testing.

Deferreds for JQuery 1.5

Anyone familiar with async programming like Node.JS or Python’s twistd library will be familiar with deferreds. Its usually a simple nuisance to re-implement when needed, so it’s nice to hear that’s not an issue anymore with JQuery’s $.when & $.then methods

Really useful guide here

What does this mean?

Say you’ve got a compound action you want to complete. For example a user clicks on a leaf in a tree like directory
menu. Now you want to update both the menu to add any possible sub nodes of that leaf PLUS update a content panel and once its finished, maybe update the hash tag to the current page’s url.

 
  $.when( updateMenu(), updateContent() )
     .success( function(){
           console.log("Both menu & content panel have been updated!");
      })
     .fail( function(){
           console.log("Oh noes, we didn't finish... try again?");
      });

That’s pretty much the gist of deferreds in a nutshell. Furthermore it appears that the author of this fantastic addition to jQuery really grokked the concept of deferreds because you can chain one deferred result to multiple child deferred’s allowing for cascading events to fire in response to one event.

Return to canvas tag

Currently in between clients and waiting for the silent alpha of my delicious clone to wrap up….so its back to experiments with the canvas tag.

That means back to my unframework canvas library Ping. Some of the code still makes sense, but other bits are… well special. Currently there is an .ex object thats appended to the CanvasRenderingContext2D internal class and it works, but what I’m thinking of is re-working the code so that they’re added post-instantiation like a factory.

 
canvasMaker = function(elemId, options){
    var element = document.getElementById(elemId);
    var context = element.getContext("2d");
    //Here is where all the extension methods would be dynamically assigned to the 2d canvas instance
    wrappedContext = wrapContext(context);
    //Maybe add a singleton check around the bulk of this that keys on the elemId
    return wrappedContext;
}

The problem I’m trying to work around specifically is the need should ever arise to have n+1 managed tags on the same document. Currently there is so many hardwired references that it would be impossible to have the two cooperate without collisions and undesirable behavior.

Canvas tag: Collision detection & pixel decay

UPDATED: March 14, 2011 here

Continuing my tests/experiments with the Canvas tag has led to the Ping prototype. I had 3 minimal things I wanted to accomplish: Detecting the intersection of a 360 degree arc of ray/line segments to previously defined in map shapes; a visual decay/fade out of intersection points on the canvas, and lastly a test of performance. In addition I decided to experiment with another approach to Javascript object construction in the hopes of getting a performance gain.
Continue reading