From 702f09d0de0b2fee9a7aeda22658745f76df291b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=8D=8E=E6=B8=85?= <18691022700@163.com> Date: Mon, 22 Dec 2025 17:43:32 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E5=96=84=E6=8A=A2=E7=BA=A2=E5=8C=85?= =?UTF-8?q?=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- application/common/library/RedpacketLua.php | 30 ++++++++++++--------- 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/application/common/library/RedpacketLua.php b/application/common/library/RedpacketLua.php index e5359ae6..952f24b2 100644 --- a/application/common/library/RedpacketLua.php +++ b/application/common/library/RedpacketLua.php @@ -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