[Cson original] HTML5 game framework cngamejs development record (core function module)

Source: Internet
Author: User

Returned directory

1. cngamejs frameworkCodeOrganization

The core function module provides convenience for subsequent framework development and game development,The entire framework is in a closure to avoid global scope contamination. Then, each module is placed in its own closure to make the separation of different modules clearer.. Therefore, the module division of our framework is as follows:

 
(Function(Win, undefined ){//Largest Closure

VaRFun1 =Function(){//Common methods for each module
}

//Each small module has its own closure.

} (Window, undefined)

So how can we further divide other small modules? In order to facilitate each small module to have its own namespace, and in their respective closuresTo add a register method, which can expand its modules in different namespaces.First, we need to pass in the namespace name. This method generates the namespace object for us, and then we execute our own method to perform corresponding extension operations for the namespace object:

 

/**
* Generate a namespace and perform corresponding operations
**/
Register:Function(Namespace, func ){
VaRNsarr = namespace. Split (".");
VaRParent = win;
For(VaRI = 0, Len = nsarr. length; I <Len; I ++ ){
(TypeofParent [nsarr [I] = 'undefined') & (parent [nsarr [I] = {});
Parent = parent [nsarr [I];
}
If(Func ){
Func. Call (parent,This);
}
ReturnParent;
}

As shown above, you can first split the input namespace string, then generate the object, and then execute the user-passed function for extension operations, as shown below:

Cngame. Register ("cngame. Core ",Function(){This. Func =Function(){}});

In this way, the core module can be generated and the func method can be added to the module. The Code organization of our framework looks like this:

 ( function  (Win, undefined) {
var cngame = {
Register: function (namespace, Handler) {

}< BR >}< br> /* core module */
cngame. register ("core", function () {
/// Add the module content
})
/* input module */
cngame. register ("input", function () {
/// Add the module content
})
win [" cngame "] = cngame;

}) (window, undefined);


2. Framework Initialization

When the framework is initialized, the objects to be saved include the canvas object, context object, canvas position, and size. Let's first look at the initialization function:

         /*  *
* Initialization
* */
Init: Function (ID, options ){
Options = options | {};
This . Canvas = This . Core. $ (ID | "canvas ");
This . Context = This . Canvas. getcontext ('2d ');
This . Width = options. Width | 800;
This . Height = options. Height | 600;
This . Title = This . Core. $ ('title') [0];
Canvaspos = getcanvaspos ( This . Canvas );
This . X = canvaspos [0] | 0;
This . Y = canvaspos [1] | 0;
This . Canvas. width = This . Width;
This . Canvas. Height =This . Height;
This . Canvas. style. Left = This . X + "PX ";
This . Canvas. style. Top = This . Y + "PX ";

},

It is very simple to save some initialization values for future use. In addition, we can note that the getcanvaspos method is called to obtain the location parameter of the canvas. This parameter cyclically obtains the offsetparent of the object and overlays offsetleft and offsettop to obtain the location of the canvas on the page. The function source code is as follows:

/**
* Obtain the location of the canvas on the page.
**/
VaRGetcanvaspos =Function(Canvas ){
VaRLeft = 0;
VaRTop = 0;
While(Canvas. offsetparent ){
Left + = canvas. offsetleft;
Top + = canvas. offsettop;
Canvas = canvas. offsetparent;

}
Return[Left, top];

}

 

3. tool function module

Then we can use the above register method to add the first module: Core module. This module is also very simple. The main function is to add tool functions to facilitate subsequent framework development and user game development. This section contains some common tool functions, such as getting elements by ID, prototype inheritance, object replication, and event binding.. NOTE: If compatibility with different browsers is involved, you can set the function based on the browser at the beginning, instead of determining the browser type each time and then performing corresponding operations, which improves efficiency.. Take event binding as an example:

         /*  *
Event binding
* */
This . Bindhandler = ( Function (){

If (Window. addeventlistener ){
Return Function (ELEM, type, Handler ){
ELEM. addeventlistener (type, handler, False );

}
}
Else If (Window. attachevent ){
Return Function (ELEM, type, Handler ){
ELEM. attachevent ("On" + type, Handler );
}
}
})();

Return different functions based on browser features in advance, so that you do not need to judge the browser features for later use to improve efficiency.

The source code of all tool functions is attached, so this module is not described in detail as it is very simple.

 /*  *
*
* Basic tool function module
*
* */
Cngame. Register ("cngame. Core ", Function (CG ){
/* *
Get elements by ID
* */
This . $ = Function (ID ){
Return Document. getelementbyid (ID );
};
/* *
Get elements by Tag Name
* */
This . $ = Function (Tagname, parent ){
Parent = parent | document;
Return Parent. getelementsbytagname (tagname );
};
/* *
Retrieve elements by Class Name
* */
This . $ Class = Function (Classname, parent ){
VaR Arr = [], result = [];
Parent = parent | document;
Arr = This . $ ("*");
For ( VaR I = 0, Len = arr. length; I <Len; I ++ ){
If ("" + Arr [I]. classname + ""). indexof ("" + classname + "")> 0 ){
Result. Push (ARR [I]);
}
}
Return Result;
};
/* *
Event binding
* */
This . Bindhandler = ( Function (){

If (Window. addeventlistener ){
Return Function (ELEM, type, Handler ){
ELEM. addeventlistener (type, handler, False );

}
}
Else If (Window. attachevent ){
Return Function (ELEM, type, Handler ){
ELEM. attachevent ("On" + type, Handler );
}
}
})();
/* *
Event relief
* */
This . Removehandler = ( Function (){
If (Window. removeeventlisterner ){
Return Function (ELEM, type, Handler ){
ELEM. removeeventlisterner (type, handler, False );

}
}
Else If (Window. detachevent ){
Return Function (ELEM, type, Handler ){
ELEM. detachevent ("On" + type, Handler );
}
}
})();
/* *
Get event object
* */
This . Geteventobj = Function (Eve ){
Return Eve | win. event;
};
/* *
Obtain the event target object
* */
This . Geteventtarget = Function (Eve ){
VaR Eve = This . Geteventobj (Eve );
Return Eve.tar GET | Eve. srcelement;
};
/* *
Disable default behavior
* */
This . Preventdefault = Function (Eve ){
If (Eve. preventdefault ){
Eve. preventdefault ();
}
Else {
Eve. returnvalue = False ;
}

};
/* *
Get the style of Object Computing
* */
This . Getcomputerstyle = ( Function (){
VaR Body = Document. Body;
If (Body. currentstyle ){
Return Function (ELEM ){
Return ELEM. currentstyle;
}
}
Else If (Document. defaultview. getcomputedstyle ){
Return Function (ELEM ){
Return Document. defaultview. getcomputedstyle (ELEM, Null );
}
}

})();
/* *
Whether it is undefined
* */
This . Isundefined = Function (ELEM ){
Return Typeof ELEM = 'undefined ';
},
/* *
Array or not
* */
This . Isarray = Function (ELEM ){
Return Object. Prototype. tostring. Call (ELEM) = "[object array]";
};
/* *
Object type?
* */
This . Isobject = Function (ELEM ){
Return ELEM = Object (ELEM );
};
/* *
String type?
* */
This . Isstring = Function (ELEM ){
Return Object. Prototype. tostring. Call (ELEM) = "[object string]";
};
/* *
Whether the data type is Numeric
* */
This . Isnum = Function (ELEM ){
Return Object. Prototype. tostring. Call (ELEM) = "[object number]";
};
/* *
* Copy Object Attributes
* */
This . Extend = Function (Destination, source, iscover ){
VaR Isundefined = This . Isundefined;
(Isundefined (iscover) & (iscover = True );
For (VaR Name In Source ){
If (Iscover | isundefined (destination [name]) {
Destination [name] = source [name];
}

}
Return Destination;
};
/* *
* Prototype inherited object
* */
This . Inherit = Function (Child, parent ){
VaR Func = Function (){};
Func. Prototype = parent. Prototype;
Child. Prototype = New Func ();
Child. Prototype. constructor = child;
Child. Prototype. Parent = parent;
};

});

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.