Corona SDK - 如何在使用随机数时避免重复函数的出现

我正在制作一款无尽跑酷游戏,对于障碍物,我使用一个表格和随机数来随机选择要生成的障碍物函数。我现在有 15 个函数,它们根据随机生成选择的数字生成不同的障碍物。问题在于,如果生成器生成了 5,该函数将运行,障碍物出现在屏幕上。不幸的是,有时生成器会在选择前一个数字后再次选择相同的数字。所以再次是 5。发生的情况是障碍物没有完成过渡就从屏幕上消失了,而物理仍然存在,并从开始的位置重新开始。这是我正在使用的代码:``` local function ranGen() local obs = {} if ast1 [a] .isVisible == false then obs [#obs + 1] = 1 end if ast2 [b] .isVisible == false then obs [#obs + 1] = 2 end if ast3 [c] .isVisible == false then obs [#obs + 1] = 3 end if ast4 [d] .isVisible == false then obs [#obs + 1] = 4 end if ast5 [e] .isVisible == false then obs [#obs + 1] = 5 end if ast6 [f] .isVisible == false then obs [#obs + 1] = 6 end local function random () -local random = obs [math.random(#obs)]; local index = math.random(#obs) local obstacle = obs [index] local num = {obstacle} if obstacle == 1 and obstacle ~ = num then opMove1 () elseif obstacle == 2 and obstacle ~ = num then opMove2 () elseif obstacle == 3 and obstacle ~ = num then opMove3 () elseif obstacle == 4 and if obstacle ~ = num then opMove4 () elseif obstacle == 5 and obstacle ~ = num then opMove5 () elseif obstacle == 6 and if obstacle ~ = num then opMove6 () elseif obstacle == num then random () end最初编码的思想是如果障碍物生成了 1,则 num 将是 1。如果障碍物再次生成 1,它将跳过第一个 if 语句并进入最后一个 elseif 语句,然后再次运行生成,直到生成了一个不同于 1 的数字。我认为这种实现应该是正确的,但问题仍然存在。我试图使它起作用的方法是,当随机数生成时,我希望避免在已经生成一个随机数之后再次生成相同的随机数。现在如果生成 5、2、5,那就没问题了。我只是想避免在已经有障碍功能重复之后立即重复相同的障碍功能。有人看到我做错了什么,或者能给我一些指导吗?感谢您的阅读!

点赞
用户2964945
用户2964945

一种方法是在生成新的随机数时跟踪以前的随机数,并在新随机数生成时进行比较。它可以看起来像这样:

-- 这将跟踪以前的随机数
-- 所以如果当前随机数相同,我们将重新选择
-- 设置为大于 #obs 的值
local previousRandom = 999

-- 生成与以前不同的新随机数
local function getRandom()
    local currentRandom

    -- 循环,直到当前随机数与先前的不同
    repeat
        currentRandom = math.random(#obs)
    until currentRandom ~= previousRandom

    -- 记得将上一次设置为当前值
    previousRandom = currentRandom

    return currentRandom
end
2015-04-21 15:30:50