您的位置:首页 > 移动开发 > Cocos引擎

cocos -js 实现计算器功能

2016-07-19 17:17 423 查看
var HelloWorldLayer = cc.Layer.extend({
_mainUI:null,
_lab:null,
TOTAL:18,
//输入的数
_tempValue: null,
//第一个输入的数
_firstDate: null,
//第二个输入的数
_secondDate: null,
//运算符
_tempType:null,

ctor:function () {
this._super();
this._init();
},
_init:function(){
this._tempValue="";
this._mainUI =ccs.load(res.main_json).node;
this.addChild(this._mainUI);
this._lab=ccui.helper.seekWidgetByName(this._mainUI,"result_lab");
//设置文本内容
this._addEvent();
},
//添加按钮点击事件
_addEvent:function(){
var btn;
for(var i=0;i<this.TOTAL;i++){
btn=this._getWidgetByName(this._mainUI,"btn_"+i);
btn.addTouchEventListener(this._inputHandler.bind(this),this._mainUI);
}
},
//点击按钮的回调方法
_inputHandler:function(sender,type){
if(type == ccui.Widget.TOUCH_ENDED){
var str =sender.name.split("btn_")[1];
if(str<= 10)this._checkInput(str);
else if(str == 11) this._checkResult();
else if(str <= 15) this._checkCreactor(str);
else if(str == 17) this._clearShow();
}
},
/*检查输入结果*/
_checkResult:function(){
this._secondDate=parseFloat(this._getLabString());
this._tempValue = "";
switch ( this._tempType){
case "12":
this._firstDate += this._secondDate;
break;
case "13":
this._firstDate -= this._secondDate;
break;
case "14":
this._firstDate *= this._secondDate;
break;
case "15":
this._firstDate /= this._secondDate;
break;
}
this._setLabString(this._firstDate);
},
/**检查运算符*/
_checkCreactor:function(str){
this._firstDate= parseFloat(this._getLabString());
this._tempType= str;
this._tempValue = "";
},

_checkInput:function(value){
var str = value;
if(this._getLabString()=="0"){
if(value == 10) this._tempValue = "0.";
else this._tempValue = str;
}else {
if (value == 10) str = (this._tempValue.indexOf(".") >= 0 ? "" : ".");
this._tempValue += str;
}
this._setLabString(this._tempValue);

},
//清除显示
_clearShow:function(){
this._tempValue = "";
this._setLabString("0");
},

//设置文本内容
_setLabString:function(str){
this._lab.setString(str);
},
_getLabString: function(){
return this._lab.getString()
},
_getWidgetByName:function(par,name){
return  ccui.helper.seekWidgetByName(par,name);
},

});
//获取对象
getWidgetByname =function(par,name){
return ccui.helper.seekWidgetByName(par.name);
},
//获取加载外部节点
getWidgetByname =function(source){
return ccs.load(source).node;
};

var HelloWorldScene = cc.Scene.extend({
onEnter:function () {
this._super();
var layer = new HelloWorldLayer();
this.addChild(layer);
}
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: