Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Learning Cocos2d-JS Game Development
Learning Cocos2d-JS Game Development

Learning Cocos2d-JS Game Development: Learn to create robust and engaging cross-platform HTML5 games using Cocos2d-JS

Arrow left icon
Profile Icon Emanuele Feronato
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.9 (11 Ratings)
Paperback Jan 2015 188 pages 1st Edition
eBook
$9.99 $19.99
Paperback
$32.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Emanuele Feronato
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.9 (11 Ratings)
Paperback Jan 2015 188 pages 1st Edition
eBook
$9.99 $19.99
Paperback
$32.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$9.99 $19.99
Paperback
$32.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Learning Cocos2d-JS Game Development

Chapter 2. Adding Interactivity – The Making of a Concentration Game

By definition, a game is interactive in some way. Players have to be part of it by doing things. The simplest form of interactivity is clicking or touching tiles in the game.

A Concentration game is simple to explain, but it will cover some new and important concepts, such as:

  • Creating multiple instances of game assets
  • Extending classes to improve its capabilities. Actually, there are no classes in JavaScript, but they are emulated using variables and prototypes
  • Adding gradients
  • Making assets react to clicks and touches
  • Changing sprite images on the fly
  • Adding text labels
  • Removing sprites from the game

By the end of the chapter, you will be able to create a full Concentration game using space for customization.

As the project created in the previous chapter is more than just a Hello World game and rather acts as a blueprint for all your future projects, you'll start building our Concentration game out of the...

Creating multiple instances of game assets

The first thing you have to do in the making of a Concentration game is draw the tiles that you will use in the game. Here are the pictures used for the covered tiles and the eight different tiles that could be potentially matched, all saved in the assets folder, as explained in the previous chapter:

Creating multiple instances of game assets

Each tile is a 64 x 64 PNG file, where the covered tile is called cover.png, while the tile to be matched is named with a progressive number from 0 to 7: tile_0, tile_1, until tile_7. This is because the actual board tile values will be stored in an array whose values will range from 0 to 7, and it will be easy to assign value 0 to tile_0, value 1 to tile_1, and so on.

With these nine files in the assets folder, you are ready to load them, thanks to the loadassets.js file located in the src folder of our project:

var gameResources = ["assets/cover.png",
  "assets/tile_0.png",
  "assets/tile_1.png",
  "assets/tile_2...

Adding a gradient background

A quick and easy way to improve the background is to add a gradient. Most of the skies and sceneries you see in the background of your favorite games are just gradients.

You are going to add a gradient layer conveniently called gradient to the game simply by adding these two lines to gamescript.js:

var gameScene = cc.Scene.extend({
  // same as before
});

var game = cc.Layer.extend({
  init:function () {
    this._super();
    var gradient = cc.LayerGradient.create(cc.color(0,0,0,255), cc.color(0x46,0x82,0xB4,255));
    this.addChild(gradient);
    for(i=0;i<16;i++){
      var tile = cc.Sprite.create("assets/cover.png");
      this.addChild(tile,0);
      tile.setPosition(49+i%4*74,400-Math.floor(i/4)*74);
    }
  }
});

Gradient layer creation is made by the cc.LayerGradient.create method, which requires both the start and end gradient color in an RGBA (Red, Green, Blue, Alpha) format.

There are two things you need to notice about the lines that were...

Extending the Sprite class beyond its capabilities

When I say sometimes, I mean most of the time the default Cocos2d-JS classes do not let you do everything you need to do with them.

Although this might seem like a limit of Cocos2d-JS, it's one of its best features. You are provided with a basic set of classes you can extend the way you need to, meaning you can add new capabilities.

So, what does it really mean to extend a class? Imagine a real-world example: you're entering a bike shop and buying a mountain bike. Your mountain bike is a class; with this class, you can do everything you can actually do with a mountain bike, namely pedal and steer.

Unfortunately, you are a bit lazy and don't want to pedal all the time, so you buy a little motor and add it to your mountain bike. Now, you can still do everything you usually did with your bike, but you can also rest your legs, turn on the motor, and let it pedal on your behalf.

You just extended the mountain bike, created a motorized...

Making assets react to clicks and touches

There are two ways to pick a tile, irrespective of whether you are playing with a touch or mouse-driven device. You can tap on a tile or you can click on it.

Picking a tile as an initial attempt

No matter the way you use Cocos2d-JS, all in all you are creating cross-platform games. You have to tell Cocos2d-JS you are going to let the user touch or click on some tiles, so the MemoryTile class will change this way:

var MemoryTile  = cc.Sprite.extend({
  ctor:function() {
    this._super();
    this.initWithFile("assets/cover.png");
    cc.eventManager.addListener(listener.clone(), this);
  }
})

What just happened? You just added an event listener to the event manager. The event manager is the entity that triggers events fired by the game or by the player. The addListener method adds a listener to the event manager, but you don't have a listener at the moment. Let's create one:

var listener = cc.EventListener.create({
  event: cc.EventListener...

Changing sprite images on the fly

Let's now find out how to change sprite images.

Showing the tile picture

Once a tile is picked, it has to show its picture. Pictures are just a graphical representation of a tile value, which you initially store in an array called gameArray declared at the very beginning of a gamescript.js file:

var gameArray = [0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7];
vargameScene = cc.Scene.extend({
  onEnter:function () {
    // same as before
  }
});

Then, once you create a new tile, you can assign it a custom attribute called pictureValue with the value of the i-th element of gameArray:

var game = cc.Layer.extend({
  init:function () {
    this._super();
    var gradient = cc.LayerGradient.create(cc.color(0,0,0,255), cc.color(0x46,0x82,0xB4,255));
    this.addChild(gradient);
    for(i=0;i<16;i++){
      var tile = new MemoryTile();
      tile.pictureValue = gameArray[i];
      this.addChild(tile,0);
      tile.setPosition(49+i%4*74,400-Math.floor(i/4)*74);
    }
  }
...

Creating multiple instances of game assets


The first thing you have to do in the making of a Concentration game is draw the tiles that you will use in the game. Here are the pictures used for the covered tiles and the eight different tiles that could be potentially matched, all saved in the assets folder, as explained in the previous chapter:

Each tile is a 64 x 64 PNG file, where the covered tile is called cover.png, while the tile to be matched is named with a progressive number from 0 to 7: tile_0, tile_1, until tile_7. This is because the actual board tile values will be stored in an array whose values will range from 0 to 7, and it will be easy to assign value 0 to tile_0, value 1 to tile_1, and so on.

With these nine files in the assets folder, you are ready to load them, thanks to the loadassets.js file located in the src folder of our project:

var gameResources = ["assets/cover.png",
  "assets/tile_0.png",
  "assets/tile_1.png",
  "assets/tile_2.png",
  "assets/tile_3.png",
  "assets...

Adding a gradient background


A quick and easy way to improve the background is to add a gradient. Most of the skies and sceneries you see in the background of your favorite games are just gradients.

You are going to add a gradient layer conveniently called gradient to the game simply by adding these two lines to gamescript.js:

var gameScene = cc.Scene.extend({
  // same as before
});

var game = cc.Layer.extend({
  init:function () {
    this._super();
    var gradient = cc.LayerGradient.create(cc.color(0,0,0,255), cc.color(0x46,0x82,0xB4,255));
    this.addChild(gradient);
    for(i=0;i<16;i++){
      var tile = cc.Sprite.create("assets/cover.png");
      this.addChild(tile,0);
      tile.setPosition(49+i%4*74,400-Math.floor(i/4)*74);
    }
  }
});

Gradient layer creation is made by the cc.LayerGradient.create method, which requires both the start and end gradient color in an RGBA (Red, Green, Blue, Alpha) format.

There are two things you need to notice about the lines that were added:

  1. The...

Left arrow icon Right arrow icon

Description

If you are a Java developer who wants to learn about Java EE, this is the book for you. It's also ideal for developers who already have experience with the Java EE platform but would like to learn more about the new Java EE 7 features by analyzing fully functional sample applications using the new application server WildFly.

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jan 12, 2015
Length: 188 pages
Edition : 1st
Language : English
ISBN-13 : 9781784390075
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Jan 12, 2015
Length: 188 pages
Edition : 1st
Language : English
ISBN-13 : 9781784390075
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 114.97
Cocos2d Game Development Essentials
$32.99
Cocos2d-x by example (update)
$48.99
Learning Cocos2d-JS Game Development
$32.99
Total $ 114.97 Stars icon
Banner background image

Table of Contents

10 Chapters
1. Hello World – A Cross-platform Game Chevron down icon Chevron up icon
2. Adding Interactivity – The Making of a Concentration Game Chevron down icon Chevron up icon
3. Moving Sprites Around the Screen – An Endless Runner Chevron down icon Chevron up icon
4. Learn about Swipes through the making of Sokoban Chevron down icon Chevron up icon
5. Become a Musical Maestro Chevron down icon Chevron up icon
6. Controlling the Game with Virtual Pads Chevron down icon Chevron up icon
7. Adding Physics to Your Games Using the Box2D Engine Chevron down icon Chevron up icon
8. Adding Physics to Your Games Using the Chipmunk2D Engine Chevron down icon Chevron up icon
9. Creating Your Own Blockbuster Game – A Complete Match 3 Game Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.9
(11 Ratings)
5 star 45.5%
4 star 18.2%
3 star 18.2%
2 star 18.2%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Hugo Dec 14, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
As a Learning Cocos2d-JS book, this is a spectacular book, the author give a lot of examples about engine features, you can start to make your gamesusing physics(Box2D and Chipmunk), endless runner, particle, virtual pads, swipe gestures, grid levels, etc.The JS port of the Cocos2d-X engine is good, and the author is a great writer (his blog is really awesome), but, some people talks about this cross platform powers of Cocos2d-JS, that is possible to use on web and on devices, I thought that the author could give more information about, I have few questions about native development and more about to publish on web... and I'm not a complete beginner on Cocos2d-x C++ version, but the Cocos2d-x community is so active that all my questions about Android side was solved, but for web I am just starting, all examples run in every platform, you just need to know how to do it, isn't just HTML5, after you know how to use this engine for each platform in command line, isn't so complicated and it is on README file on root folder, you will see how powerful this book is and after that you will simply love it, as the title says "Learning Cocos2d-JS", this book is a powerful tool to you learn to make games, Cocos2d-JS is really fast for test, for my games the stability and performance was almost like native.
Amazon Verified review Amazon
iPaul Mar 23, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is a good intro to game development if you are a JavaScript programmer, if you are a JavaScript beginner you should probably learn some JS (there are a lot of free intros online). The author will hold your hand into building a complete cross platform game while teaching you the in and outs of Cocos2d-JS (the JavaScript version of Cocos2d-x).
Amazon Verified review Amazon
Pradyumna Mar 25, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I have worked with Cocos2D on iOS and have planned to develop cross platform games using some framework. That is when I got to know about Cocos2d-JS and this book gives you a clear cut explanation and a good flow on how to carry on with developing games and there are types of games that will be explained in the book. Thanks to Emanuele (Y)..
Amazon Verified review Amazon
Andrew McNutt Jan 27, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This was a fantastic book. There are a couple errors on the Kindle edition(the version I bought) but the code examples are all there. The different chapters each provide very useful information. I look forward to other books from this author.A little more on the book itself. This is great if you are completely new to Cocos2d-js(as I was). After reading the book I feel it gave me a solid base as to where to dive deeper on certain topics for a game I am working on. If you are new to Cocos2d-js it is well worth the money.
Amazon Verified review Amazon
CH Tan Mar 23, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
It is a good book for the beginner to learn game programming theory with the examples. (I'm new to game programming)For me it still require the beginner to learn some basic knowledge of Javascript before get into this.The explanation after the code line by line, able to help the reader understand it clearly.That was less book teach about the Cocos2d-JS right now on the market. Will looking for more books about Cocos2d-JS programming books from Emanuele Feronato. Hope will release the Advanced Game Development soon.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.