显示与math.random相同的图片?

Displaying the same picture with math.random?

我正在使用 Corona SDK,我想显示随机颜色。这是我的代码,但我的颜色总是一样的。这是为什么?

local boxColors = {
        "BoxColors/Gold.png",
        "BoxColors/Blue.png",
        "BoxColors/Green.png",
        "BoxColors/Orange.png",
        "BoxColors/Purple.png",
        "BoxColors/Rose.png",
        "BoxColors/Yellow.png"
    }

groundColor =display.newImage(boxColors[math.random(#boxColors)],0,0)

感谢您的好心人

这是我很久以前制作的一个简洁的小随机播放功能。 math.random 的随机性可能有点不确定,所以下面的函数让它更具冒险性。

func shuffleArray(myArray) 

  for i=0,30 do -- Do the below 30 times
    for temp = 1, #myArray do 
        n = math.random(1, #myArray) -- Select a random index from myArray and assign it to n.
        temp1 = myArray[temp] -- Take the loop number(temp) as an index from myArray and assign it to temp1.
        myArray[temp] = myArray[n] -- Replace the temp index taken from above with the randomly selected SoundList index.
        myArray[n] = temp1 -- Replace the randomly chosen index with the temp index.
    end
  end

return myArray -- Return the shuffled array.
end

您只需调用该函数并将一个数组传递给它,或者您可以随意编辑它!

亲切的问候,

Krivvenz.

我不知道你的代码怎么样,但我在这里试过并为我工作,我只需要在实例化新图像之前添加 groundColor:removeSelf(),因为在 Corona 中它没有被覆盖。

如果你只是改变颜色,试试这样:

local centerX = display.contentCenterX
local centerY = display.contentCenterY

local colors = {
    { 1,1,0 }, -- yellow
    { 0,0,1 }, -- blue
    { 0,1,0 }, -- green
    { 1,0,0 }, -- red
}

rect = display.newRect(centerX, centerY, 100, 100)
rect.fill = colors[math.random(#colors)]

function onTouch( event )
    if event.phase == "began" then
        rect.fill = colors[math.random(#colors)]
    end
end
rect:addEventListener( "touch", onTouch )