在corona sdk中使用数组的随机场景

时间:2014-09-23 18:03:08

标签: lua

。 。 ,我在使用composer.gotoScene运行随机场景时遇到问题,只有应用程序的第一个场景以随机形式显示。这是一个测验游戏,我不知道如何用得分调用result.lua。

实际测试:

1st attempt = scene2, scene3, scene4, scene1
2nd attempt = scene3, scene4, scene1, scene2
3rd attempt = scene4, scene1, scene2, scene3

预期产出:

1st attempt = scene3, scene1, scene4, scene2, result
2nd attempt = scene1, scene4, scene2, scene3, result

这是我的shuffle代码:

local sceneNames = {"scene1","scene2","scene3","scene4"};
for count=1, 0 do 
    sceneNames[count] = count
end



local function shuffle(t)
    local iterations = #t
    local j
    for count = iterations,2, -1 do
        j = math.random(count)
        t[count], t[j] = t[j], t[count]
    end
end

shuffle(sceneNames)

我不知道在哪里设置它或我需要做什么。 。 。请帮忙

1 个答案:

答案 0 :(得分:0)

你忘记了种子。这应该有效:

local sceneNames = {"scene1","scene2","scene3","scene4"}

local function shuffle(t)
    local iterations = #t
    for count = iterations,2, -1 do
        local j = math.random(count)
        t[count], t[j] = t[j], t[count]
    end
end

要使用,请运行

math.randomseed(os.time())
shuffle(sceneNames)

多次。每一次,做

for i,v in ipairs(sceneNames) do print(i,v) end

看到序列每次都随机变化。