首页 > 其他 > 详细

Lua随机选取表中元素&处理

时间:2014-04-04 22:37:30      阅读:1225      评论:0      收藏:0      [点我收藏+]
mapmonsters{
	{
		mapid = 150404,
		monsters = {
		
			{monsterId = 100402, weight = 147},
			{monsterId = 100403, weight = 147},
			{monsterId = 100404, weight = 147},
			{monsterId = 100406, weight = 147},
			{monsterId = 100405, weight = 147},
			{monsterId = 100502, weight = 5},
			{monsterId = 100503, weight = 5},
			{monsterId = 100504, weight = 5},
			
		}
	},
}

math.randomseed(tostring(os.time()):reverse():sub(1, 6)) -- 随机种子


function offline_random_monster(x)
	totalWeight = 0
	tempRate = {}
	bingo = 0

	-- 处理权重
	for i=1, table.getn(mapmonsters) do
		if mapmonsters[i].mapid == x then	-- 找到了地图
			bingo = i;
			for j = 1, table.getn(mapmonsters[i].monsters) do
				totalWeight = totalWeight + mapmonsters[i].monsters[j].weight
				table.insert(tempRate, totalWeight)
			end
		end
	end


	keynum = math.random(totalWeight)	-- 保存找到的地图索引

	for k=1, table.getn(tempRate)-1 do
		if keynum <= tempRate[k] then
			return mapmonsters[bingo].monsters[k].monsterId
		elseif keynum > tempRate[k] and keynum <= tempRate[k+1] then
			return mapmonsters[bingo].monsters[k+1].monsterId
		end

	end
end


Lua随机选取表中元素&处理,布布扣,bubuko.com

Lua随机选取表中元素&处理

原文:http://blog.csdn.net/lightupheaven/article/details/22940905

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!