使用 Corona SDK 中的数组来生成随机场景。

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

实际测试:

第一次尝试= scene2,scene3,scene4,scene1
第二次尝试= scene3,scene4,scene1,scene2
第三次尝试= scene4,scene1,scene2,scene3

预期输出:

第一次尝试= scene3,scene1,scene4,scene2,result
第二次尝试= 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)

我不知道在哪里设置这个或需要做什么。. .请帮帮我

点赞
用户869951
用户869951

Your forgot to seed. This should work:

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

将以上代码复制并执行,你会发现每次结果都一样,因为 Lua 的随机数生成是计算机伪随机,需要先“种子化”才能得到不同的随机数。这个函数会将列表随机打乱。

使用前,请运行:

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

进行种子化并打乱列表。每次运行时,可以运行:

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

查看列表随机排序的不同结果。

2014-09-29 22:18:51