Building an RPG in JavaScript with Crafty

by Louis Stowasser

The day has come where JavaScript games are possible and not only possible but simple. This article will show you how easy it is to create games in JavaScript using the canvas tag and even basic divs with the help of a new game engine called Crafty.


Tutorial Details

The game we will be creating in this tutorial is the basics of an RPG. This way you will be able to add more and more features once you learn the basics of Crafty. View the demo.

Before we get started there are some key concepts to learn which may differ to what you are used to. Crafty uses something called an Entity Component system. Entities are your game objects (players, enemies, walls, balls) and Components are objects or a set of functions and properties that can be applied to any entity which will inherit the functionality. If you are used to Object Oriented programming, this is similar to one level of multiple inheritence. This is useful in game development because it avoids long chains of inheritence and messy polymorphism.

Crafty uses syntax similar to jQuery by having a selector engine to select entities by their components.

Crafty("mycomponent")
Crafty("hello 2D component")
Crafty("hello, 2D, component")

The first selector will return all entities that has the component "mycomponent". The second will return all entities that has "hello" and "2D" and "component" whereas the last will return all entities that has at least one of those components.

If you are a bit confused, fear not, first hand experience will make it click. So let's dive in!


Step 1 Supplies

First of all we need some sprites. I made some 16x16 sprites in Photoshop for the grass, flowers, bushes and the player's animation.

We need to setup our Crafty game. The skeleton of a Crafty game is an HTML file with a script tag pointing to the Crafty JS file and another script tag for the game logic (in this example, game.js). I added a few basic styles to place the stage in the center of the screen and give it a black border.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <script type="text/javascript" src="http://craftyjs.com/release/0.3/crafty.js"></script>
  <script type="text/javascript" src="game.js"></script>
  <title>My Crafty Game</title>
  <style>
    body, html { margin:0; padding: 0; overflow:hidden; font-family:Arial; font-size:20px }
    #cr-stage { border:2px solid black; margin:5px auto; color:white }
  </style>
</head>
<body>
</body>
</html>

The skeleton code of a Crafty game is quite simple.

window.onload = function() {
  //start crafty
  Crafty.init(50, 400, 320);
  Crafty.canvas();
};

When the window object is loaded initialize Crafty with an FPS (frames per second) of 50, a width and height of 400 and 320 respectively, and create a canvas element. The reason for these dimensions is so 25 16x16 tiles can fit horizontally and 20 vertically.

Note: Crafty.canvas() is required for any canvas drawing. It can be left out if all drawing is done with DOM.

Now we have the basics of a Crafty game! Every game you create with Crafty will have generally the same skeleton code so feel free to use this as a template. Next up is setting up scenes.


Step 2 Scenes

Scenes in Crafty are a quick way to organise game objects and easily change between screens or levels. In our RPG we want a loading scene and the main scene which will be the game.

window.onload = function() {
  // Start crafty
  Crafty.init(50, 400, 320);
  Crafty.canvas();

  // The loading screen that will display while our assets load
  Crafty.scene("loading", function() {
    // Load takes an array of assets and a callback when complete
    Crafty.load(["sprite.png"], function() {
      Crafty.scene("main"); //when everything is loaded, run the main scene
    });
    
    // Black background with some loading text
    Crafty.background("#000");
    Crafty.e("2D, DOM, text").attr({w: 100, h: 20, x: 150, y: 120})
      .text("Loading")
      .css({"text-align": "center"});
  });
  
  // Automatically play the loading scene
  Crafty.scene("loading");
};

Woah, where did all that code come from? First we declare the loading scene and tell it what to display when it is played then run it straight away. Crafty.scene() is used to declare a scene as well as play it. In the loading scene we preload some assets, set the background to black and add some loading text. Crafty.load() is used to preload assets such as sounds or images and once completed, call a function. In our game we want to play the main scene as soon as the assets are loaded.

Note: If you need an entity to persist through changing scenes, simply add a component called persist.


Step 3 Sprites

Remember that sprite map from earlier? It's time to use that in the game and get some visuals here. Crafty has an inbuilt method to splice sprite maps into individual components that can be applied to any 2D entity.

window.onload = function() {
  // Start crafty
  Crafty.init(50, 400, 320);
  Crafty.canvas();

  // Turn the sprite map into usable components
  Crafty.sprite(16, "sprite.png", {
    grass1: [0,0],
    grass2: [1,0],
    grass3: [2,0],
    grass4: [3,0],
    flower: [0,1],
    bush1:  [0,2],
    bush2:  [1,2],
    player: [0,3]
  });

  // The loading screen that will display while our assets load
  Crafty.scene("loading", function() {
    // Load takes an array of assets and a callback when complete
    Crafty.load(["sprite.png"], function() {
      Crafty.scene("main"); //when everything is loaded, run the main scene
    });
    
    // Black background with some loading text
    Crafty.background("#000");
    Crafty.e("2D, DOM, text").attr({w: 100, h: 20, x: 150, y: 120})
      .text("Loading")
      .css({"text-align": "center"});
  });
  
  // Automatically play the loading scene
  Crafty.scene("loading");
};

The first argument is the tile size (in our case is 16 pixels by 16 pixels). This defaults to 1 if left out. The next argument is the path to the sprite map. Finally the last argument is an object where the key is the label and the value is an array for where the particular sprite is located in the image. The values are multiplied by 16 so you need only give the amount of tiles from the top left. If a sprite takes up a width or height greater than one tile, simple add it to the array following this format.

[x, y, w, h]

You may notice that not all of the sprites in the sprite map have been labelled. This is because the sprites form an animation which we will add later.

window.onload = function() {
  // Start crafty
  Crafty.init(50, 400, 320);
  Crafty.canvas();

  // Turn the sprite map into usable components
  Crafty.sprite(16, "sprite.png", {
    grass1: [0,0],
    grass2: [1,0],
    grass3: [2,0],
    grass4: [3,0],
    flower: [0,1],
    bush1:  [0,2],
    bush2:  [1,2],
    player: [0,3]
  });

  // Method to randomy generate the map
  function generateWorld() {
    // Generate the grass along the x-axis
    for (var i = 0; i < 25; i++) {
      // Generate the grass along the y-axis
      for (var j = 0; j < 20; j++) {
        grassType = Crafty.randRange(1, 4);
        Crafty.e("2D, canvas, grass" + grassType)
          .attr({x: i * 16, y: j * 16});

        // 1/50 chance of drawing a flower and only within the bushes
        if (i > 0 && i < 24 && j > 0 && j < 19 && Crafty.randRange(0, 50) > 49) {
          Crafty.e("2D, DOM, flower, animate")
            .attr({x: i * 16, y: j * 16})
            .animate("wind", 0, 1, 3)
            .bind("enterframe", function() {
              if (!this.isPlaying())
                this.animate("wind", 80);
            });
        }
      }
    }

    // Create the bushes along the x-axis which will form the boundaries
    for (var i = 0; i < 25; i++) {
      Crafty.e("2D, canvas, wall_top, bush"+Crafty.randRange(1,2))
        .attr({x: i * 16, y: 0, z: 2});
      Crafty.e("2D, canvas, wall_bottom, bush"+Crafty.randRange(1,2))
        .attr({x: i * 16, y: 304, z: 2});
    }

    // Create the bushes along the y-axis
    // We need to start one more and one less to not overlap the previous bushes
    for (var i = 1; i < 19; i++) {
      Crafty.e("2D, canvas, wall_left, bush" + Crafty.randRange(1,2))
        .attr({x: 0, y: i * 16, z: 2});
      Crafty.e("2D, canvas, wall_right, bush" + Crafty.randRange(1,2))
        .attr({x: 384, y: i * 16, z: 2});
    }
  }

  // The loading screen that will display while our assets load
  Crafty.scene("loading", function() {
    // Load takes an array of assets and a callback when complete
    Crafty.load(["sprite.png"], function() {
      Crafty.scene("main"); //when everything is loaded, run the main scene
    });

    // Black background with some loading text
    Crafty.background("#000");
    Crafty.e("2D, DOM, text").attr({w: 100, h: 20, x: 150, y: 120})
      .text("Loading")
      .css({"text-align": "center"});
  });

  // Automatically play the loading scene
  Crafty.scene("loading");
};

generateWorld() is a function that will create entities to fill up the stage. This is the first time we have created an entity so I will go over that first. The function to create an entity is simple Crafty.e(). That's it. You can also pass a string of components to add which will just call the .addComponent() method. Have a look at the following lines of code:

grassType = Crafty.randRange(1, 4);
Crafty.e("2D, canvas, grass" + grassType)
  .attr({x: i * 16, y: j * 16});

When we spliced the sprite map, we had four types of grass components/labels: grass1, grass2, grass3 and grass4. Using a little helper method, Crafty.randRange(), we generate a random number between 1 and 4 to decide which grass tile to use and apply it to the entity. You will notice we are also adding some odd looking components: 2D and canvas. 2D is a very important component which gives the entity and x and y position, width and height (called .w and .h), rotation, alpha and some basic rectangle calculations. The other component, canvas, tells Crafty how to draw the entity and with this component obviously on the canvas element. You can just as easy use the DOM component and it will instead draw it as a <DIV>.

Tip: DOM is usually always faster than canvas and if you notice sluggish performance in a canvas entity, try using DOM. It will look and act no different.

The rest of the method generates a boundary around the stage so the player can't walk off. This uses the bush sprite. You will also notice that these boundary entities have a component either wall_left, wall_right, wall_up or wall_down. The only purpose they serve is as a label. There is no functionality inherited.


Step 4 Entities

Let's create the player entity already. The source code is getting quite large so I will just show the code from the main scene.

Crafty.scene("main", function() {
  generateWorld();

  // Create our player entity with some premade components
  var player = Crafty.e("2D, DOM, player, controls, animate, collision")
    .attr({x: 160, y: 144, z: 1})
    .animate("walk_left", 6, 3, 8)
    .animate("walk_right", 9, 3, 11)
    .animate("walk_up", 3, 3, 5)
    .animate("walk_down", 0, 3, 2);
});

We call the generateWorld() function from earlier and create a player entity with some premade components: animate, controls and collision. Animate is a component to create animations for sprites. Similar to Crafty.scene(), you add an animation and play it with the same method with different arguments. The first argument is the name of the animation, the x position in the sprite map, y position in the sprite map and then the x position of the last frame in the sprite map (assuming the sprites all have the same y. If they don't pass an array of arrays similar to the Crafty.sprite() method).

The controls component transforms keyboard input into Crafty events. Use .bind() to listen to an event. The events triggered in the controls component is keyup and keydown. The collision component is a very basic method of calling a function if an entity intersects another entity with a specific component (this is where the labels come in handy such as wall_left, wall_right, etc etc).

Note: The .attr() method is used to modify properties of the entity. In this case we position the player in the middle of the screen.


Step 5 Components

It's about time we really utilise the Entity Component system and create our first component. The component we need right now is something to control movement. There already exists two components for movement (twoway and fourway) but we want finer control and don't want diagonal movement.

To create a component use the function Crafty.c(), where the first argument is the name of the component and the second is an object with properties and functions. To have a function execute as soon as it is added to an entity, create a function called init. If you need more information before initialising, best practice is to create a function with the same name as the component (commonly known as a constructor).

Crafty.scene("main", function() {
  generateWorld();
  Crafty.c('CustomControls', {
    __move: {left: false, right: false, up: false, down: false},    
    _speed: 3,

    CustomControls: function(speed) {
      if (speed) this._speed = speed;
      var move = this.__move;

      this.bind('enterframe', function() {
        // Move the player in a direction depending on the booleans
        // Only move the player in one direction at a time (up/down/left/right)
        if (move.right) this.x += this._speed; 
        else if (move.left) this.x -= this._speed; 
        else if (move.up) this.y -= this._speed;
        else if (move.down) this.y += this._speed;
      }).bind('keydown', function(e) {
        // Default movement booleans to false
        move.right = move.left = move.down = move.up = false;

        // If keys are down, set the direction
        if (e.keyCode === Crafty.keys.RA) move.right = true;
        if (e.keyCode === Crafty.keys.LA) move.left = true;
        if (e.keyCode === Crafty.keys.UA) move.up = true;
        if (e.keyCode === Crafty.keys.DA) move.down = true;

        this.preventTypeaheadFind(e);
      }).bind('keyup', function(e) {
        // If key is released, stop moving
        if (e.keyCode === Crafty.keys.RA) move.right = false;
        if (e.keyCode === Crafty.keys.LA) move.left = false;
        if (e.keyCode === Crafty.keys.UA) move.up = false;
        if (e.keyCode === Crafty.keys.DA) move.down = false;

        this.preventTypeaheadFind(e);
      });

      return this;
    }
  });

  // Create our player entity with some premade components
  var player = Crafty.e("2D, DOM, player, controls, CustomControls, animate, collision")
    .attr({x: 160, y: 144, z: 1})
    .CustomControls(1)
    .animate("walk_left", 6, 3, 8)
    .animate("walk_right", 9, 3, 11)
    .animate("walk_up", 3, 3, 5)
    .animate("walk_down", 0, 3, 2);
});

Our component has two properties: __move and _speed. The first is an object of booleans used to indicate which direction the player should be moving. The second is how many pixels the character should move by or speed. We then just have one function, the constructor. We could easily just use an init method here and assume a speed of 3, but we want a speed of 1 so a constructor is needed to indicate that.

We use the .bind() method a fair bit in this component. The enterframe event is called on every frame (depending on the FPS) so when the callback is triggered, it will move the player in a direction depending on which direction is true and by the amount/speed we previously decided.

The other two events, keydown and keyup, simply check which key has been pressed (derived from the event object passed as an argument) and then set the movement boolean. There is a reason why we don’t simply move the player as soon as the key is down. The keydown event will trigger once then have a short pause before calling it over and over until a key is up. We don’t want that pause so we use the enterframe event to continuously move the player. The keyup callback does the same as keydown but in reverse, sets the movement booleans to false if the key has been released.

You will also notice our player entity has our new component in the component list as well as calling the constructor. Our player should be able to move now.

Note: Using an underscore before property or function names is the convention we're using to convey that it is private.


Step 6 Animation

Now that the player can move, we want to play the animation we setup earlier

// Create our player entity with some premade components
var player = Crafty.e("2D, DOM, player, controls, CustomControls, animate, collision")
  .attr({x: 160, y: 144, z: 1})
  .CustomControls(1)
  .animate("walk_left", 6, 3, 8)
  .animate("walk_right", 9, 3, 11)
  .animate("walk_up", 3, 3, 5)
  .animate("walk_down", 0, 3, 2)
  .bind("enterframe", function(e) {
    if (this.__move.left) {
      if (!this.isPlaying("walk_left"))
        this.stop().animate("walk_left", 10);
    }
    if (this.__move.right) {
      if (!this.isPlaying("walk_right"))
        this.stop().animate("walk_right", 10);
    }
    if (this.__move.up) {
      if (!this.isPlaying("walk_up"))
        this.stop().animate("walk_up", 10);
    }
    if (this.__move.down) {
      if (!this.isPlaying("walk_down"))
        this.stop().animate("walk_down", 10);
    }
  }).bind("keyup", function(e) {
    this.stop();
  });

On the enterframe event we want to know the direction the player is moving (using the movement booleans created in our component) and play the appropriate animation. We don't want to play it if it is already playing however, so we use the .isPlaying() function. If it isn’t playing, stop whatever animation is playing with the .stop() function and play the correct one. Playing an animation is a matter of calling .animate() with the name of the animation and a duration in frames. Because we only have 3 frames for the animation, we want it to be fairly quick. We also want to stop any animation if a key is up.


Step 7 Collision

Crafty provides collision detection between any two convex polygons. A collision exists when two entities intersect each other. We use the pre-made collision component to detect collisions with the boundary so the player can't leave the stage.

// Create our player entity with some premade components
var player = Crafty.e("2D, DOM, player, controls, CustomControls, animate, collision")
  .attr({x: 160, y: 144, z: 1})
  .CustomControls(1)
  .animate("walk_left", 6, 3, 8)
  .animate("walk_right", 9, 3, 11)
  .animate("walk_up", 3, 3, 5)
  .animate("walk_down", 0, 3, 2)
  .bind("enterframe", function(e) {
    if (this.__move.left) {
      if (!this.isPlaying("walk_left"))
        this.stop().animate("walk_left", 10);
    }
    if (this.__move.right) {
      if (!this.isPlaying("walk_right"))
        this.stop().animate("walk_right", 10);
    }
    if (this.__move.up) {
      if (!this.isPlaying("walk_up"))
        this.stop().animate("walk_up", 10);
    }
    if (this.__move.down) {
      if (!this.isPlaying("walk_down"))
        this.stop().animate("walk_down", 10);
    }
  }).bind("keyup", function(e) {
    this.stop();
  }).collision()
  .onhit("wall_left", function() {
    this.x += this._speed;
    this.stop();
  }).onhit("wall_right", function() {
    this.x -= this._speed;
    this.stop();
  }).onhit("wall_bottom", function() {
    this.y -= this._speed;
    this.stop();
  }).onhit("wall_top", function() {
    this.y += this._speed;
    this.stop();
  });

Remember those labels we put on the bushes earlier? Now is when they become useful. The function .collision() is the constructor and accepts a polygon object (see Crafty.polygon) or if empty will create one based on the entities x, y, w and h values.

.onhit() takes two arguments, the first being the component to look for collisions and the second being the function called if a collision occurs. If the player collides with any entity with the component wall_left, we need to move the player away from the wall at the same speed it is moving towards it. We need to do this for all other walls so depending on the direction, move the player in the opposite direction at the same speed. I also added the .stop() function so that it doesn't keep animating when it isn't moving.


Step 8 Final Code

Putting together everything we learnt, we should have the following code in game.js

Now you should have the basics of an RPG. If you need any support using Crafty there are forums and documentation.