用Quick Cocos2dx做一个连连看(二)

今天完成了以下内容:

1 成对生成SpriteItem

2 重排接口制作完成

3 SpriteItem的选择逻辑

主要代码如下:

 1 function MainScene:onEnter()
 2     local item
 3     local item0
 4     local temptype = 1
 5     for i=1,32 do
 6         temptype = math.floor(math.random(0,10))
 7         item = SpriteItem.new()
 8         item:setData(temptype)
 9         item:addTo(self.layer)
10         item:setName(string.format("item%d", i))
11         self.items[i] = item
12         item:setPos(math.floor((i-1)%row),math.floor((i-1)/row))
13 
14         item0 = SpriteItem.new()
15         item0:setData(temptype)
16         item0:addTo(self.layer)
17         self.items[i+32] = item0
18         item0:setName(string.format("item%d", i+32))
19         item0:setPos(math.floor((i+31)%row),math.floor((i+31)/row))
20     end
21 
22     self:shuffle(self.items)
23 
24     self.layer:addNodeEventListener(cc.NODE_TOUCH_EVENT, handler(self, self.onTouched))
25     self.layer:setTouchEnabled(true)
26 end

 

顺序重排的方法:

 1 function MainScene:shuffle(t)
 2     local  len = #t
 3     for i=1,len*2 do
 4         local a = math.floor(math.random(len))
 5         local b = math.floor(math.random(len))
 6         
 7         if a ~= b then
 8             t[a],t[b] = t[b],t[a]
 9             t[a]:setPos(math.floor((a-1)%row),math.floor((a-1)/row))
10             t[b]:setPos(math.floor((b-1)%row),math.floor((b-1)/row))
11             --printInfo("swap item %d : %d", a,b)
12         end
13     end
14     --[[i = 1
15     for i=1,len do
16         print(t[i]:getName())
17     end]]
18 end

 

选择逻辑:根据屏幕上的坐标点取得对应的SpriteItem

 1 function MainScene:getItem( posx, posy )
 2     --printInfo("getItem %d : %d", posx, posy)
 3     
 4     local px = math.round((posx - startX)/50)
 5     local py = math.round((posy-startY)/50)
 6     if px > 8 or py > 8 then
 7         return
 8     end
 9     local index = row * py + px + 1
10     local item = self.items[index]
11     
12     return item
13 end

 

当前效果图如下:

 

posted @ 2014-12-29 19:13  Ado_On  阅读(312)  评论(0编辑  收藏  举报