Lua 游戏 实现合并同类物品

写到前面的话:
作者从毕业开始一直从事游戏开发,提供大量游戏实战模块代码及案例供大家学习与交流,希望以下知识可以带来一些帮助,如有任何疑问,请加群641792143交流与学习

``

 --根据type和id生成一个唯一的索引
 local function generateIndex( ty,id )
    	assert(type(ty) == "number")
    	assert(type(id) == "number")
    	return ty * 1000000 + id
    end
    local function ungenerateIndex( index )
    	local ty = math.modf( index / 1000000 )  -- 取整数
    	local id = math.fmod( index, 1000000 )    -- 取余数
    	return ty,id
    end
    
    --合并奖励
    function mergeDropAward(awards)
    	assert(type(awards) == "table")
    	if #awards <= 1 then return awards end
    	-- 合并
    	local temp = {}
    	local tempx = {}
    	local pos = 0
    	for _, award in ipairs(awards) do
    		assert(type(award) == "table")
    		local index = generateIndex( award.type,award.id )
    		local p = temp[index]
    		if p then
    			local re = tempx[p]
    			re.count = re.count + award.count
    		else
    			table.insert(tempx,{type = award.type,id = award.id,count = award.count})
    			pos = pos + 1
    			temp[index] = pos
    		end
    	end
    
    	return tempx
    end
    
    local awards = 
    {
    	{type = 1,id = 1,count = 10},
    	{type = 2,id = 1,count = 10},
    	{type = 1,id = 1,count = 10},
    	{type = 4,id = 1,count = 10},
    	{type = 4,id = 1,count = 10},
    	{type = 1,id = 1,count = 10},
    }
    
    local rewards = mergeDropAward(awards)
    
    for _,v in ipairs(rewards) do
    	print(v.type,v.id,v.count)
    end
发布了43 篇原创文章 · 获赞 1 · 访问量 2325

猜你喜欢

转载自blog.csdn.net/lpl312905509/article/details/100195498