从cocos2d-html5中提取出来的,用做前端开发的框架——cc.js
从cocos2d-html5中提取出来的,用做前端开发的框架——cc.js
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011 Zynga Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
/* Managed JavaScript Inheritance
* Based on John Resig's Simple JavaScript Inheritance http://ejohn.org/blog/simple-javascript-inheritance/
* MIT Licensed.
*/ /**
* @namespace
*/
var cc = cc || {}; //
function ClassManager(){
//tells own name
return arguments.callee.name || (arguments.callee.toString()).match(/^function ([^(]+)/)[1];
}
ClassManager.id=(0|(Math.random()*998));
ClassManager.instanceId=(0|(Math.random()*998));
ClassManager.compileSuper=function(func, name, id){
//make the func to a string
var str = func.toString();
//find parameters
var pstart = str.indexOf('(');
var pend = str.indexOf(')');
var params = str.substring(pstart+1, pend);
params = params.trim(); //find function body
var bstart = str.indexOf('{');
var bend = str.lastIndexOf('}');
var str = str.substring(bstart+1, bend); //now we have the content of the function, replace this._super
//find this._super
while(str.indexOf('this._super')!= -1)
{
var sp = str.indexOf('this._super');
//find the first '(' from this._super)
var bp = str.indexOf('(', sp); //find if we are passing params to super
var bbp = str.indexOf(')', bp);
var superParams = str.substring(bp+1, bbp);
superParams = superParams.trim();
var coma = superParams? ',':''; //find name of ClassManager
var Cstr = arguments.callee.ClassManager(); //replace this._super
str = str.substring(0, sp)+ Cstr+'['+id+'].'+name+'.call(this'+coma+str.substring(bp+1);
}
return Function(params, str);
};
ClassManager.compileSuper.ClassManager = ClassManager;
ClassManager.getNewID=function(){
return this.id++;
};
ClassManager.getNewInstanceId=function(){
return this.instanceId++;
}; (function () {
var initializing = false, fnTest = /\b_super\b/;
var releaseMode = (document['ccConfig'] && document['ccConfig']['CLASS_RELEASE_MODE']) ? document['ccConfig']['CLASS_RELEASE_MODE'] : null;
if(releaseMode) {
console.log("release Mode");
} /**
* The base Class implementation (does nothing)
* @class
*/
cc.Class = function () {
}; /**
* Create a new Class that inherits from this Class
* @param {object} prop
* @return {function}
*/
cc.Class.extend = function (prop) {
var _super = this.prototype; // Instantiate a base Class (but only create the instance,
// don't run the init constructor)
var prototype = Object.create(_super); var classId = ClassManager.getNewID();
ClassManager[classId] = _super;
// Copy the properties over onto the new prototype. We make function
// properties non-eumerable as this makes typeof === 'function' check
// unneccessary in the for...in loop used 1) for generating Class()
// 2) for cc.clone and perhaps more. It is also required to make
// these function properties cacheable in Carakan.
var desc = { writable: true, enumerable: false, configurable: true };
for (var name in prop) {
if(releaseMode && typeof prop[name] == "function" && typeof _super[name] == "function" && fnTest.test(prop[name])) {
desc.value = ClassManager.compileSuper(prop[name], name, classId);
Object.defineProperty(prototype, name, desc);
} else if(typeof prop[name] == "function" && typeof _super[name] == "function" && fnTest.test(prop[name])){
desc.value = (function (name, fn) {
return function () {
var tmp = this._super; // Add a new ._super() method that is the same method
// but on the super-Class
this._super = _super[name]; // The method only need to be bound temporarily, so we
// remove it when we're done executing
var ret = fn.apply(this, arguments);
this._super = tmp; return ret;
};
})(name, prop[name]);
Object.defineProperty(prototype, name, desc);
} else if(typeof prop[name] == "function") {
desc.value = prop[name];
Object.defineProperty(prototype, name, desc);
} else{
prototype[name] = prop[name];
}
}
prototype.__instanceId = null; // The dummy Class constructor
function Class() {
this.__instanceId = ClassManager.getNewInstanceId();
// All construction is actually done in the init method
if (this.ctor)
this.ctor.apply(this, arguments);
} Class.id = classId;
// desc = { writable: true, enumerable: false, configurable: true,
// value: XXX }; Again, we make this non-enumerable.
desc.value = classId;
Object.defineProperty(prototype, '__pid', desc); // Populate our constructed prototype object
Class.prototype = prototype; // Enforce the constructor to be what we expect
desc.value = Class;
Object.defineProperty(Class.prototype, 'constructor', desc); // And make this Class extendable
Class.extend = arguments.callee; //add implementation method
Class.implement = function (prop) {
for (var name in prop) {
prototype[name] = prop[name];
}
};
return Class;
}; Function.prototype.bind = Function.prototype.bind || function (bind) {
var self = this;
return function () {
var args = Array.prototype.slice.call(arguments);
return self.apply(bind || null, args);
};
}; })(); //my only
cc.ArrayRemoveObject = function (arr, delObj) {
for (var i = 0, l = arr.length; i < l; i++) {
if (arr[i] == delObj) {
arr.splice(i, 1);
break;
}
}
};
cc.log = function (message) {
if (!cc.IS_SHOW_DEBUG_ON_PAGE) {
console.log.apply(console, arguments);
} else {
cc._logToWebPage(message);
}
};
cc.NODE_TAG_INVALID = -1; cc.s_globalOrderOfArrival = 1; cc.Node = cc.Class.extend(/** @lends cc.Node# */{
_zOrder:0,
// children (lazy allocs),
_children:null,
_parent:null,
_tag:cc.NODE_TAG_INVALID,
_orderOfArrival:0,
_initializedNode:false,
_initNode:function () {
this._children = [];
this._initializedNode = true;
},
ctor:function () {
if (this._initializedNode === false)
this._initNode();
return true;
},
init:function () {
if (this._initializedNode === false)
this._initNode();
return true;
},
_child:function(func){
var arr=this._children
if(arr.length){
for (i = 0; i < arr.length; i++) {
if(false==arr[i]._child(func)){
return false
}
}
} if(func.apply(this)==false){
return false
}
return true
},
_arrayMakeObjectsPerformSelector:function (array, callbackType) {
if (!array || array.length === 0)
return; var i, len = array.length,node;
var nodeCallbackType = cc.Node.StateCallbackType;
switch (callbackType) {
case nodeCallbackType.onEnter:
for (i = 0; i < len; i++) {
node = array[i];
if (node)
node.onEnter();
}
break;
case nodeCallbackType.onExit:
for (i = 0; i < len; i++) {
node = array[i];
if (node)
node.onExit();
}
break;
case nodeCallbackType.cleanup:
for (i = 0; i < len; i++) {
node = array[i];
if (node)
node.cleanup();
}
break;
case nodeCallbackType.updateTransform:
for (i = 0; i < len; i++) {
node = array[i];
if (node)
node.updateTransform();
}
break;
case nodeCallbackType.sortAllChildren:
for (i = 0; i < len; i++) {
node = array[i];
if (node)
node.sortAllChildren();
}
break;
default :
throw "Unknown callback function";
break;
}
}, getZOrder:function () {
return this._zOrder;
}, _setZOrder:function (z) {
this._zOrder = z;
}, setZOrder:function (z) {
this._setZOrder(z);
if (this._parent)
this._parent.reorderChild(this, z);
}, reorderChild:function (child, zOrder) {
if(!child)
throw "cc.Node.reorderChild(): child must be non-null";
child.setOrderOfArrival(cc.s_globalOrderOfArrival++);
child._setZOrder(zOrder);
this._reorderChildDirty = true;
}, getChildrenCount:function () {
return this._children.length;
}, getChildren:function () {
return this._children;
}, isRunning:function () {
return this._running;
}, getParent:function () {
return this._parent;
}, setParent:function (Var) {
this._parent = Var;
}, getTag:function () {
return this._tag;
}, setTag:function (Var) {
this._tag = Var;
}, getChildByTag:function (aTag) {
var __children = this._children;
if (__children != null) {
for (var i = 0; i < __children.length; i++) {
var node = __children[i];
if (node && node._tag == aTag)
return node;
}
}
//throw "not found";
return null;
}, addChild:function (child, zOrder, tag) {
if(!child)
throw "cc.Node.addChild(): child must be non-null";
if (child === this) {
cc.log('cc.Node.addChild(): An Node can\'t be added as a child of itself.');
return;
} if (child._parent !== null) {
cc.log("cc.Node.addChild(): child already added. It can't be added again");
return;
} var tmpzOrder = (zOrder != null) ? zOrder : child._zOrder;
child._tag = (tag != null) ? tag : child._tag;
this._insertChild(child, tmpzOrder);
child._parent = this; if (this._running) {
child.onEnter();
}
}, removeFromParent:function (cleanup) {
if (this._parent) {
if (cleanup == null)
cleanup = true;
this._parent.removeChild(this, cleanup);
}
}, removeChild:function (child, cleanup) {
// explicit nil handling
if (this._children.length === 0)
return; if (cleanup == null)
cleanup = true;
if (this._children.indexOf(child) > -1)
this._detachChild(child, cleanup); }, removeChildByTag:function (tag, cleanup) {
if(tag === cc.NODE_TAG_INVALID)
cc.log("cc.Node.removeChildByTag(): argument tag is an invalid tag"); var child = this.getChildByTag(tag);
if (child == null)
cc.log("cocos2d: removeChildByTag(tag = " + tag + "): child not found!");
else
this.removeChild(child, cleanup);
}, removeAllChildren:function (cleanup) {
// not using detachChild improves speed here
var __children = this._children;
if (__children != null) {
if (cleanup == null)
cleanup = true;
for (var i = 0; i < __children.length; i++) {
var node = __children[i];
if (node) {
// IMPORTANT:
// -1st do onExit
// -2nd cleanup
if (this._running) {
node.onExit();
}
if (cleanup)
node.cleanup();
// set parent nil at the end
node.setParent(null);
}
}
this._children.length = 0;
}
}, _detachChild:function (child, doCleanup) {
// IMPORTANT:
// -1st do onExit
// -2nd cleanup
if (this._running) {
child.onExit();
} // If you don't do cleanup, the child's actions will not get removed and the
// its scheduledSelectors_ dict will not get released!
if (doCleanup)
child.cleanup(); // set parent nil at the end
child.setParent(null); cc.ArrayRemoveObject(this._children, child);
}, _insertChild:function (child, z) {
this._children.push(child);
child._setZOrder(z);
this._reorderChildDirty = true;
}, setOrderOfArrival:function (Var) {
this._orderOfArrival = Var;
}, sortAllChildren:function () {
if (this._reorderChildDirty) {
var _children = this._children;
var i, j, length = _children.length,tempChild; // insertion sort
for (i = 0; i < length; i++) {
var tempItem = _children[i];
j = i - 1;
tempChild = _children[j]; //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
while (j >= 0 && ( tempItem._zOrder < tempChild._zOrder ||
( tempItem._zOrder == tempChild._zOrder && tempItem._orderOfArrival < tempChild._orderOfArrival ))) {
_children[j + 1] = tempChild;
j = j - 1;
tempChild = _children[j];
}
_children[j + 1] = tempItem;
} //don't need to check children recursively, that's done in visit of each child
this._reorderChildDirty = false;
}
}, onEnter:function () {
this._running = true;//should be running before resumeSchedule
this._arrayMakeObjectsPerformSelector(this._children, cc.Node.StateCallbackType.onEnter); }, onExit:function () {
this._running = false;
this._arrayMakeObjectsPerformSelector(this._children, cc.Node.StateCallbackType.onExit); },
cleanup:function () {
// timers
this._arrayMakeObjectsPerformSelector(this._children, cc.Node.StateCallbackType.cleanup);
},
updateTransform:function () {
// Recursively iterate over children
this._arrayMakeObjectsPerformSelector(this._children, cc.Node.StateCallbackType.updateTransform);
} }); cc.Node.create = function () {
return new cc.Node();
}; cc.Node.StateCallbackType = {onEnter:1, onExit:2, cleanup:3, updateTransform:5, sortAllChildren:7}; cc.Sprite=cc.Node.extend({
})
cc.Sprite.create = function () {
return new cc.Sprite();
};
cc.Layer=cc.Node.extend({
})
cc.Layer.create = function () {
return new cc.Layer();
};
cc.Scene=cc.Node.extend({
})
cc.Scene.create = function () {
return new cc.Scene();
};
cc.Middle=function(){
var next=function(func1,func2){
return function(){
var arg=Array.prototype.slice.call(arguments)
var arr=[].concat(arg)
arg.push(function(){
func2.apply(this,arr)
})
return func1.apply(this,arg);
}
}
var arg=Array.prototype.slice.call(arguments)
var func=arg[arg.length-1]
for(var i=arg.length-2;i>=0;i--){
func=next(arg[i],func)
}
return func
}
cc.Director={
_runningScene:null,
replaceScene:function(scene){
if(this._runningScene){
this._runningScene.onExit()
}
scene.onEnter()
scene._arrayMakeObjectsPerformSelector(scene._children, cc.Node.StateCallbackType.sortAllChildren);
this._runningScene=scene }
}
cc.js源码
不好意思又一次用别人的东西………
cocos2d-html5框架无疑是一款优秀、出色的跨平台的开源游戏框架,历经众多产品的考验,核心类cc.Node采用多叉树的结构、cc.Class类可以方便自由的扩充新的对象,一切都是如此美好,使用了一年多时间的cocos2d框架,也做过一些jsb的移植开发,深刻的感受到了coco2d做游戏开发的便利和强大,赞一个!
同时我也在想,前端开发是不是也能方便的用到cocos2d呢?特别是现在的移动web开发,页面的交互逻辑特别多,跟游戏如此相似,所以小wo努力思考、客观实践,终于把coco2d中的核心cc.Class和cc.Node提取出来了(去掉与游戏相关的属性和方法),新添加了cc.Middle(http://www.cnblogs.com/caoke/p/middle.html),也重写了下cc.Director的replaceScene.
工具准备好了,剩下就等着下周1的项目开始了
var layer1=cc.Layer.extend({
context:$("#id"),
name:true,
init:function(){
},
initAnimate:function(){
var sprite=new cc.Sprite
sprite.name=22
this.addChild(sprite,2)
var sprite=new cc.Sprite
sprite.name=32
this.addChild(sprite,1)
var sprite=new cc.Sprite
sprite.name=42
this.addChild(sprite,1)
var sprite=new cc.Sprite
this.addChild(sprite,1)
},
//点击交互事件
initMenu:function(){
},
})
var Scene1=cc.Scene.extend({
init:function(){
this._super()
var layer=new layer1()
layer.init()
this.addChild(layer)
}
})
var scene=new Scene1()
scene.init()
//显示页面
scene.onEnter()
最终效果: http://weixin.koo.cn/test.html
从cocos2d-html5中提取出来的,用做前端开发的框架——cc.js的更多相关文章
- html5中视频播放问题总结
html5中视频播放问题总结 文章 1.问题一 框架? 加个标签就OK! <video id="video1" src="/video1.mp4" con ...
- web前端开发学习:jQuery的原型中的init
web前端开发学习:jQuery的原型中的init 有大量web前端开发工具及学习资料,可以搜群[ web前端学习部落22群 ]进行下载,遇到学习问题也可以问群内专家以及课程老师哟 jQuery.fn ...
- html5中的video标签和audio标签
不管是否承认,flash早已不像过往那样如日中天了.亚马逊全面放弃flash.苹果放弃flash.安卓也放弃了移动端的flash支持.事实上flash已经不太适合web开发了,因为HTML5中的vid ...
- html5中time元素详解
html5中time元素详解 一.总结 一句话总结: time的使用的话主要是将时间放在datetime属性里面:<time datetime="2015-10-22"> ...
- html5中canvas的使用 获取鼠标点击页面上某点的RGB
1.html5中的canvas在IE9中可以跑起来.在IE8则跑不起来,这时候就需要一些东西了. 我推荐这种方法,这样显得代码不乱. <!--[if lt IE9]> <script ...
- [数据科学] 从csv, xls文件中提取数据
在python语言中,用丰富的函数库来从文件中提取数据,这篇博客讲解怎么从csv, xls文件中得到想要的数据. 点击下载数据文件http://seanlahman.com/files/databas ...
- html5中新增的form表单属性
html5中新增两个表单属性,分别autocomplete和novalidate属性 1.autocomplete属性 该属性用于控制自动完成功能的开启和关闭.可以设置表单或者input元素,有两个属 ...
- HTML5 中的 canvas 画布(一)
---恢复内容开始--- 在HTML5中新添加的元素,canvas 现在支持 IE9+的版本 注意:HTML5 <canvas> 元素用于图形的绘制,通过脚本 (通常是JavaScript ...
- 如何使用免费PDF控件从PDF文档中提取文本和图片
如何使用免费PDF控件从PDF文档中提取文本和图片 概要 现在手头的项目有一个需求是从PDF文档中提取文本和图片,我以前也使用过像iTextSharp, PDFBox 这些免费的PD ...
随机推荐
- 3.Strings 字符串如何工作?----对缓冲区的理解。
修改Hello World程序向特定的人问好. #include <iostream> #include <string> int main() { std::string n ...
- 3.Dynamic Layout 动态布局。在槽中处理布局
在应用程序中,一个界面的布局基本都是固定的. 在这个实例中,我们把管理布局的代码放在槽中.这样点击一次按钮,触发槽.布局改变一次.这样就成为一个动态布局. (一) 水平和竖直布局改变 横向: 纵向: ...
- 9.python 系统批量运维管理器之Fabric模块
前面介绍了paramiko,pexpect模块,今天来说比较适合大型应用自动化部署的模块,或者执行系统命令的模块Fabric. Fabric 是一个 Python 的库,同时它也是一个命令行工具.它提 ...
- [redis]redis-cluster搭建
1.概述: redis是一种工作在内存里no-sql的非关系型数据库,广泛应用于缓存需求,以减少大量的数据访问对数据库的压力,还很适合用来充当整个互联网架构中各级之间的cache 比如lvs的4层转发 ...
- 浅析C语言中assert的用法(转)
原文地址:http://www.jb51.net/article/39685.htm 以下是对C语言中assert的使用方法进行了介绍,需要的朋友可以参考下. assert宏的原型定义在<ass ...
- (转)ASP.NET MVC4+EasyUI+EntityFrameWork权限管理系统——数据库的设计(一)
原文地址:http://www.cnblogs.com/cmsdn/p/3371576.html 快一年没写博客了,这段时间感觉好迷茫,写点博客,记录一下自己的成长过程,希望对大家也有帮助 先上图 一 ...
- mobiscroll_2.15.1
var opt_sex = { theme: 'ios', lang: 'zh', formatValue: function (d) { return d.join(','); }, customW ...
- Head First HTML与CSS、XHTML (中文版).(Elisabeth Freeman) PDF扫描版
面对那些晦涩的html书你不禁要问:“难道要成为专家之后才能读懂这些?”那么,你应该选择<head first html与css.xhtml(中文版)>真正来学习html.这本书对你来说, ...
- wifi 定位
前一天跟某电信公司一位朋友聊天: 问:电信用户现在能占手机用户多少比例? 答:(??) 问:把cdma给了电信,其实就是给个根鸡肋. 答:呃,看怎么说.对于电信来说,毕竟拿到了移动牌照. 问:工作行不 ...
- 今天遇到的传入的表格格式数据流(TDS)远程过程调用(RPC)协议流不正确的解决方案
传入的表格格式数据流(TDS)远程过程调用(RPC)协议流不正确.参数 3 ("@UserName"): 数据类型 0xE7 的数据长度或元数据长度无效. 今天在做数据同步的时候遇 ...