Introducing Cocos2d-js adding it to the languages used to develop a Farm Heroes Saga prototype

Read all posts about "" game

Today I want to show you what you can do with Cocos2d-JS, and as a first, brief tutorial, I will show you how to create the same stuff I made for the 3rd part of the Farm Heroes Saga tutorial.

Cocos2d-JS is an open-source 2d game framework, released under MIT License. It includes Cocos2d-html5 and Cocos2d-x JavaScript Bindings, making Cocos2d cross platforms between browsers and native application.

On top of the framework provided by Cocos2d-JS, games can be written in Javascript, using API that is COMPLETELY COMPATIBLE between Cocos2d-html5 and Cocos2d-x JavaScript Bindings.

Cocos2d-html5 project can be easily run on browsers which supports HTML5. It also supports running game code as native application in Cocos2d-x JavaScript Bindings without or with little modification.

This is the content of index.html:

<!DOCTYPE html>
<html>
	<head>
		<script src="cocos2d.js"></script>
	</head>
	<body style="padding:0;margin:0;background-color:#000000;">
		<canvas id="gameCanvas"></canvas>
	</body>
</html>

There’s nothing interesting in it, just look at the canvas which does not have width and height, they will be set from Cocos2d. Also, a JavaScript file called cocos2d.js is called, and here is its content:

(function () {
	var d = document;
	var c = {
		tag:"gameCanvas", 
		engineDir:"../cocos2d/",
		appFiles:[
     		"src/resource.js",
     		"src/game.js"
    		]
	};

	var fn;
	window.addEventListener("DOMContentLoaded", fn = function() {
		this.removeEventListener("DOMContentLoaded", fn, false);
		var s = d.createElement("script");
		s.src = c.engineDir + "jsloader.js";
		document.ccConfig = c;
		s.id = "cocos2d-html5";
		d.body.appendChild(s);
	});
})();

This is mostly a simplified version of the “Hello World” example you can find in Cocos2d, I just want you to have a look at these few lines:

Line 4: this is the value of the id attribute of the canvas you can see at line 7 in index.html file

Line 5: the path to Cocos2d itself.

Lines 6-9: an array of files to load in order to make the game work.

Another file required by Cocos2d is main.js, which is also just a template file, let me show you:

var cocos2dGame = cc.Application.extend({
	config:document["ccConfig"],
	ctor:function(scene) {
     	this._super();
     	this.startScene = scene;
     	cc.setup(this.config["tag"]);
     	cc.AppController.shareAppController().didFinishLaunchingWithOptions();
    	},
	applicationDidFinishLaunching:function () {
		cc.EGLView.getInstance().resizeWithBrowserSize(true);
		cc.EGLView.getInstance().setDesignResolutionSize(320,480,cc.RESOLUTION_POLICY.SHOW_ALL);
		var director = cc.Director.getInstance();
     	cc.LoaderScene.preload(g_resources, function () {
          	director.replaceScene(new this.startScene());
		},this);
		return true;
	}
});

var myGame = new cocos2dGame(gameScene);

I would point you attention to these lines:

Line 10: resizing the game when the browser is resized

Line 11: defining game resolution and scaling mode

Line 20: the game itself, called myGame

Now, everything is inside the two files declared at lines 6-9 inside cocos2d.js. resource.js is just an array containing all the resources (images) to be preloaded:

var g_resources = [
    	"res/tile_1.png",
    	"res/tile_2.png",
    	"res/tile_3.png",
    	"res/tile_4.png",
    	"res/tile_5.png",
    	"res/tile_6.png",
    	"res/tile_7.png",
	"res/tile_8.png",
];

and obviously game.js is the core of the game, which logic has already been explained in the post creation of a match 3 game like Farm Heroes Saga using any language – step 2.

var gameScene = cc.Scene.extend({
	onEnter:function () {
     	this._super();
     	var gameLayer = new game();
     	gameLayer.init();
		this.addChild(gameLayer);
	}
});

var FIELDSIZE = 8;
var TILETYPES = 8;
var TILESIZE = 36;
var OFFSETX = 16;
var OFFSETY = 50;
var gameArray = new Array(FIELDSIZE*FIELDSIZE);

var game = cc.Layer.extend({
	init:function () {
		this._super();	
		createLevel();	
		drawLevel(this);
	}
});

function rowNumber(i){
	return Math.floor(i/FIELDSIZE);
}

function colNumber(i){
	return i%FIELDSIZE;
}

function isHorizontalMatch(i){
	return colNumber(i)>=2 && gameArray[i]==gameArray[i-1] && gameArray[i] == gameArray[i-2] && rowNumber(i)==rowNumber(i-2);
}

function isVerticalMatch(i){
	return rowNumber(i)>=2 && gameArray[i]==gameArray[i-FIELDSIZE] && gameArray[i] == gameArray[i-2*FIELDSIZE];
}

function createLevel(){
	for(i=0;i<FIELDSIZE*FIELDSIZE;i++){
		do{
	     	gameArray[i]=Math.ceil(Math.random()*TILETYPES);
	     }while (isHorizontalMatch(i) || isVerticalMatch(i));
	} 
	console.log(gameArray);
}

function drawLevel(g){
	var s = cc.Director.getInstance().getWinSize();
	for(i=0;i<FIELDSIZE*FIELDSIZE;i++){
		var tile = gameArray[i];
		g.item = cc.Sprite.create("res/tile_"+tile+".png");
		g.item.setPosition(i%FIELDSIZE*TILESIZE+OFFSETX+TILESIZE/2,s.height-(Math.floor(i/FIELDSIZE)*TILESIZE+OFFSETY+TILESIZE/2));
		g.addChild(g.item,0);	  
	}
}

That said, I would only let you have a look at lines 54-56 which create and place game elements on stage. Also, remember Cocos2d has the (0,0) origin in the lower left corner rather than the upper left corner we are used to, and the registration point of the graphic assets in in their center rather than in the upper left corner we are used to.

And this is the result, a 320×480 game upscaled to 360×540 to let you see how it works:

And this is how we ported the work made until now on Farm Heroes Saga to Cocos2d-JS. Download the source code with all required libraries.

Get the most popular Phaser 3 book

Through 202 pages, 32 source code examples and an Android Studio project you will learn how to build cross platform HTML5 games and create a complete game along the way.

Get the book

214 GAME PROTOTYPES EXPLAINED WITH SOURCE CODE
// 1+2=3
// 100 rounds
// 10000000
// 2 Cars
// 2048
// A Blocky Christmas
// A Jumping Block
// A Life of Logic
// Angry Birds
// Angry Birds Space
// Artillery
// Astro-PANIC!
// Avoider
// Back to Square One
// Ball Game
// Ball vs Ball
// Ball: Revamped
// Balloon Invasion
// BallPusher
// Ballz
// Bar Balance
// Bejeweled
// Biggification
// Block it
// Blockage
// Bloons
// Boids
// Bombuzal
// Boom Dots
// Bouncing Ball
// Bouncing Ball 2
// Bouncy Light
// BoxHead
// Breakout
// Bricks
// Bubble Chaos
// Bubbles 2
// Card Game
// Castle Ramble
// Chronotron
// Circle Chain
// Circle Path
// Circle Race
// Circular endless runner
// Cirplosion
// CLOCKS - The Game
// Color Hit
// Color Jump
// ColorFill
// Columns
// Concentration
// Crossy Road
// Crush the Castle
// Cube Jump
// CubesOut
// Dash N Blast
// Dashy Panda
// Deflection
// Diamond Digger Saga
// Don't touch the spikes
// Dots
// Down The Mountain
// Drag and Match
// Draw Game
// Drop Wizard
// DROP'd
// Dudeski
// Dungeon Raid
// Educational Game
// Elasticity
// Endless Runner
// Erase Box
// Eskiv
// Farm Heroes Saga
// Filler
// Flappy Bird
// Fling
// Flipping Legend
// Floaty Light
// Fuse Ballz
// GearTaker
// Gem Sweeper
// Globe
// Goat Rider
// Gold Miner
// Grindstone
// GuessNext
// Helicopter
// Hero Emblems
// Hero Slide
// Hexagonal Tiles
// HookPod
// Hop Hop Hop Underwater
// Horizontal Endless Runner
// Hundreds
// Hungry Hero
// Hurry it's Christmas
// InkTd
// Iromeku
// Jet Set Willy
// Jigsaw Game
// Knife Hit
// Knightfall
// Legends of Runeterra
// Lep's World
// Line Rider
// Lumines
// Magick
// MagOrMin
// Mass Attack
// Math Game
// Maze
// Meeblings
// Memdot
// Metro Siberia Underground
// Mike Dangers
// Mikey Hooks
// Nano War
// Nodes
// o:anquan
// One Button Game
// One Tap RPG
// Ononmin
// Pacco
// Perfect Square!
// Perfectionism
// Phyballs
// Pixel Purge
// PixelField
// Planet Revenge
// Plants Vs Zombies
// Platform
// Platform game
// Plus+Plus
// Pocket Snap
// Poker
// Pool
// Pop the Lock
// Pop to Save
// Poux
// Pudi
// Pumpkin Story
// Puppet Bird
// Pyramids of Ra
// qomp
// Quick Switch
// Racing
// Radical
// Rebuild Chile
// Renju
// Rise Above
// Risky Road
// Roguelike
// Roly Poly
// Run Around
// Rush Hour
// SameGame
// SamePhysics
// Save the Totem
// Security
// Serious Scramblers
// Shrink it
// Sling
// Slingy
// Snowflakes
// Sokoban
// Space Checkers
// Space is Key
// Spellfall
// Spinny Gun
// Splitter
// Spring Ninja
// Sproing
// Stabilize!
// Stack
// Stick Hero
// String Avoider
// Stringy
// Sudoku
// Super Mario Bros
// Surfingers
// Survival Horror
// Talesworth Adventure
// Tetris
// The Impossible Line
// The Moops - Combos of Joy
// The Next Arrow
// Threes
// Tic Tac Toe
// Timberman
// Tiny Wings
// Tipsy Tower
// Toony
// Totem Destroyer
// Tower Defense
// Trick Shot
// Tunnelball
// Turn
// Turnellio
// TwinSpin
// vvvvvv
// Warp Shift
// Way of an Idea
// Whack a Creep
// Wheel of Fortune
// Where's my Water
// Wish Upon a Star
// Word Game
// Wordle
// Worms
// Yanga
// Yeah Bunny
// Zhed
// zNumbers