Game Development Reference
In-Depth Information
}
}();
// ...
}(window));
Inside the first closure, we have defined a ns argument, which refers to the window variable because we
pass it in argument at the end. This is how you can redefine an object access name.
This ns argument is used as the “root” of all services we want to expose outside. In this example, calling
window.Service.publicFunctionGetter() will return "something" .
We could use another argument instead of window, like window.Game :
(function(ns){
// ...
}(window.Game={}));
We have set window.Game to the empty object. This assignment is optional if you have already done it
elsewhere.
A real example for our chess game
In our game, we will use Zepto on mobile and tablet platforms, and jQuery for web browsers (see the
Mobile Frameworks section). Both libraries provide almost the same API, but jQuery provides a better
fallback and support for all browsers (from IE6). Zepto is lighter and convenient for WebKit browsers that
are used by most of the smartphones and tablets today. To perform full support and have a generic code
for both libraries in total transparency, we use the following code:
(function(ns, $){
// ns namespace is defined in window.Game
// jQuery OR Zepto are available by using $
}(window.Game={}, window.jQuery||window.Zepto));
The Game class
The Game class contains all the logic of the chess game. In Listing 3-10, notice the init method, which
initializes piece positions in the game board.
Listing 3-10. init Method
ns.Game = function(o){
var self = this;
self.pieces = [];
self.whiteEated = [];
self.blackEated = [];
self.currentPlayer = 'white';
self.currentPiece = null;
self.init = function(){ // Init the chessboard pieces
var piece = function(c, t, p){ return { color: c, type: t, position: p } };
var firstRowTypes = ['rook', 'knight', 'bishop', 'queen', 'king', 'bishop',
'knight', 'rook'];
for(var i=0; i<=7; ++i) {
 
Search WWH ::




Custom Search