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

时间:2023-12-14 23:03:56

今天完成了以下内容:

1 成对生成SpriteItem

2 重排接口制作完成

3 SpriteItem的选择逻辑

主要代码如下:

 function MainScene:onEnter()
local item
local item0
local temptype =
for i=, do
temptype = math.floor(math.random(,))
item = SpriteItem.new()
item:setData(temptype)
item:addTo(self.layer)
item:setName(string.format("item%d", i))
self.items[i] = item
item:setPos(math.floor((i-)%row),math.floor((i-)/row)) item0 = SpriteItem.new()
item0:setData(temptype)
item0:addTo(self.layer)
self.items[i+] = item0
item0:setName(string.format("item%d", i+))
item0:setPos(math.floor((i+)%row),math.floor((i+)/row))
end self:shuffle(self.items) self.layer:addNodeEventListener(cc.NODE_TOUCH_EVENT, handler(self, self.onTouched))
self.layer:setTouchEnabled(true)
end

顺序重排的方法:

 function MainScene:shuffle(t)
local len = #t
for i=,len* do
local a = math.floor(math.random(len))
local b = math.floor(math.random(len)) if a ~= b then
t[a],t[b] = t[b],t[a]
t[a]:setPos(math.floor((a-)%row),math.floor((a-)/row))
t[b]:setPos(math.floor((b-)%row),math.floor((b-)/row))
--printInfo("swap item %d : %d", a,b)
end
end
--[[i = 1
for i=1,len do
print(t[i]:getName())
end]]
end

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

 function MainScene:getItem( posx, posy )
--printInfo("getItem %d : %d", posx, posy) local px = math.round((posx - startX)/)
local py = math.round((posy-startY)/)
if px > or py > then
return
end
local index = row * py + px +
local item = self.items[index] return item
end

当前效果图如下:

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