DailyJS

Making Games with JavaScript and Crafty

Louis Stowasser

Subscribe

@dailyjs

Facebook

Google+

tutorials graphics games

Making Games with JavaScript and Crafty

Posted by Louis Stowasser on .
Featured

tutorials graphics games

Making Games with JavaScript and Crafty

Posted by Louis Stowasser on .


This is a guest post by Louis Stowasser, the creator of
Crafty

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.

This tutorial will demonstrate how to build a Pokemon-style RPG with
Crafty. You'll be able to add your own features once you learn the
basics. If you'd like to see the what we'll be building, 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 inheritance. 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!

Supplies

We need to setup our Crafty game. The skeleton of a Crafty game is a
single HTML file with a script tag pointing to the Crafty JS file and
another script tag for the game logic -- in this example it's
game.js:

  My Crafty Game

    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 }

Here's a simple Crafty game skeleton:

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

When the window object is loaded, initialize Crafty with a
frames per second of 50, a width and height of 400 and 320 respectively,
and create a Canvas element. In case you're wondering, 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.

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");
};

Whoa, 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 pre-load
some assets, set the background to black and add some loading text.
Crafty.load() is used to pre-load 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.

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, simply 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 simply
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

.

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. 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 inherited functionality.

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 are 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.).

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.

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.

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.

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 entity's x, y, w and h values.

.onhit() takes two arguments, the first is the component to
watch for collisions and the second is 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.

Final Code

Putting together everything we learnt, we should have the following:
crafty-demo.js.

Now you should have the basics of an RPG!

If you need any support using Crafty, please visit the Crafty
forums
and Crafty
documentation
.