1:关于三消游戏首先第一步就是游戏的初始状态。在游戏的一开始就不能存在三个或者三个以上相连的块 不然这样游戏一开始就会自动的消除。所以第一步就是检测游戏的开始有多少个三个相连的块。检测的思路 就是遍历数组中的每一个元素,并且检测每一个块的最右边的两个块,如果最右边的两个块的颜色和第一个块的颜色相同那么就说明有三个相连的情况,并且记录下来。存在数组里。ps:检测的条件 考虑到越界的情况 ,所以在检测到列数的-2位置就停止检测。具体代码如下:
checkXl:function(){
var returnArr =[];
for(var i = 0 ; i < GAMEDATA.LINE ; i++){
for( var j = 0; j <GAMEDATA.LIST; j++){
if(i<GAMEDATA.LINE -2&&
this.spArr[i][j].type == this.spArr[i+1][j].type &&
this.spArr[i+1][j].type == this.spArr[i+2][j].type
){
returnArr.push(cc.p(i,j),cc.p(i+1,j),cc.p(i+2,j));
}
if(j<GAMEDATA.LIST -2&&
this.spArr[i][j].type == this.spArr[i][j+1].type &&
this.spArr[i][j+1].type == this.spArr[i][j+2].type
){
returnArr.push(cc.p(i,j),cc.p(i,j+1),cc.p(i,j+2));
}
}
}
return returnArr
},
所以上面的returnArr里面存的就是三个或者三个以上相连的情况的图片,
第二步就是找到三个或者三个以上相连的图片就要个这些图片更改为其他的图片。思路是在上面的三个相连的图片中随机找一个图片更改为随机的其他图片,然后运用递归函数,一直循环这个方法,就可以达到游戏一开始就没有重复的三个块。代码如下:
updateas:function(){
var sameArr = this.checkXl()
cc.log("第"+this.timeCount++ +"次",sameArr.length)
if(sameArr.length>0){
for(var index in sameArr){
var oo = sameArr[index]
this.spArr[oo.x][oo.y].setCellType()
}
this.updateas()
}else {
cc.log("生成完成")
}
}
调用上面的生成的三个相连的方法体。运用数组里面的元素更改图片 ,更改图片主要是更改cell类里面的type值具体方法如下:
setCellType:function(){
this.type = 1 +parseInt(Math.random()*4) ;
this.initWithFile("res/pic_"+this.type+".png");
},
这样就已经实现了游戏初始化的时候不会存在三个或者三个以上相连的情况了。
第三步就是实现点击交换,并且改变其在数组里面的下标。点击交换的话,因为涉及到两次的点击 所以这里要定义也一个全局的变量保存第一次点击的值。然后比较第一次和第二次点击的情况,进行一些判断,然后进行交换。需要注意的情况就是如果第二次点击的位置不在第一次点击的位置周围就不能进行交换。具体代码如下:
app类:
oldCell:null,
//点击交换
choiceJudg:function(event){
var data = event.getUserData();
if(this.oldCell == null){
this.oldCell = data;
data.changeCellOP(true)
}
else if(this.oldCell == data){
data.changeCellOP(false)
this.oldCell =null
}
else if(this.oldCell.primary.y ==data.primary.y){
if(this.oldCell.primary.x == data.primary.x+1 ||this.oldCell.primary.x == data.primary.x-1){
cc.log("左右交换")
this.exchange(this.oldCell,data)
this.oldCell.changeCellOP(false)
this.oldCell =null
}
}
else if(this.oldCell.primary.x ==data.primary.x){
if(this.oldCell.primary.y == data.primary.y+1 || this.oldCell.primary.y ==data.primary.y-1){
cc.log("上下交换")
this.exchange(this.oldCell,data)
this.oldCell.changeCellOP(false)
//data.changeCellOP(true)
this.oldCell =null
}
}
},
//传入两个点击的对象 点击交换
exchange:function(oldCell,cells){
var cell1 = oldCell.getPosition();
var cell2 = cells.getPosition();
var tool = oldCell.primary
oldCell.cellMove(cell2,cells.primary);
cells.cellMove(cell1,tool)
/*var temp = oldCell;
oldCell = cells;
cells =temp*/
var temp = this.spArr[oldCell.primary.x][oldCell.primary.y]
this.spArr[oldCell.primary.x][oldCell.primary.y] = this.spArr[cells.primary.x][cells.primary.y]
this.spArr[cells.primary.x][cells.primary.y] = temp
},
cell类:
cellMove:function(po,index){
var move = cc.moveTo(1,po);
this.runAction(move);
this.primary = index;
this.lable.setString(this.primary.x+"."+this.primary.y)
},
这样就实现了点击交换并且更改他在数组里面的值,在更改下标的时候,在块移动的时候就给下标传到移动的函数中,使的下标也跟着改变。