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

eBook
$9.99 $19.99
Paperback
$32.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
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.
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

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 Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

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 the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela