完善抢红包逻辑
This commit is contained in:
@@ -69,29 +69,35 @@ if leftCount <= 0 or leftAmount <= 0 then
|
||||
return {0, "红包已抢完", 0}
|
||||
end
|
||||
|
||||
-- 计算红包金额
|
||||
-- 计算红包金额(核心修改:适配整数金币,避免0)
|
||||
local amount = 0
|
||||
local isFinished = 0
|
||||
|
||||
if leftCount == 1 then
|
||||
-- 最后一个红包,获得剩余所有金额
|
||||
-- 最后一个红包,获得剩余所有金额(确保至少1)
|
||||
amount = leftAmount
|
||||
isFinished = 1
|
||||
else
|
||||
-- 随机算法:二倍均值法,保证公平性
|
||||
local maxAmount = leftAmount / leftCount * 2
|
||||
amount = math.random(1, math.floor(maxAmount))
|
||||
-- 确保金额不会超过剩余金额
|
||||
if amount > leftAmount then
|
||||
amount = leftAmount
|
||||
end
|
||||
-- 检查是否是最后一个(由于浮点数计算可能有误差)
|
||||
if leftCount == 1 or (leftAmount - amount) < 0.01 then
|
||||
-- 随机算法:二倍均值法(适配整数,保证最低1)
|
||||
-- 1. 计算二倍均值(整数处理,向下取整)
|
||||
local avg = leftAmount / leftCount
|
||||
local maxAmount = math.floor(avg * 2)
|
||||
-- 2. 确保最大金额至少为1,且不超过剩余金额-(剩余个数-1)(避免后续红包无金额可分)
|
||||
-- 剩余金额-(剩余个数-1):保证剩下的每个红包至少能分1个金币
|
||||
local safeMax = leftAmount - (leftCount - 1)
|
||||
maxAmount = math.min(maxAmount, safeMax)
|
||||
maxAmount = math.max(maxAmount, 1) -- 确保最小可随机值为1
|
||||
|
||||
-- 3. 随机生成1到maxAmount之间的整数(避免0)
|
||||
amount = math.random(1, maxAmount)
|
||||
|
||||
-- 4. 检查是否抢完(整数判断,无需浮点数误差处理)
|
||||
if leftCount - 1 == 1 or (leftAmount - amount) <= 0 then
|
||||
isFinished = 1
|
||||
end
|
||||
end
|
||||
|
||||
-- 更新红包数据
|
||||
-- 更新红包数据(整数处理,无小数)
|
||||
local newLeftAmount = leftAmount - amount
|
||||
local newLeftCount = leftCount - 1
|
||||
|
||||
|
||||
Reference in New Issue
Block a user