Search code examples
listfunctionluacoronasdk

Randomly choose objects and change colour of object chosen


i have 4 circles that are currently black {'c1','c2','c3','c4'}. i am trying to set it up so that one of the circles are chosen and it colour changes from black to red. i have manage to get it to print out a random entity in the circle list. but i cant get it to change the colour of the circle that is has randomly chosen. sorry i am still fairly new to this.

local composer = require( "composer" )
local scene = composer.newScene()

-- "scene:create()"
function scene:create( event )

    local sceneGroup = self.view

    local backgroundimg = display.newRect( 0,0,576,320 )
    backgroundimg.x = display.contentWidth*0.5
    backgroundimg.y = display.contentHeight*0.5
    sceneGroup:insert( backgroundimg )

    local pause = display.newImage( "image/pauseBTN.png" )
    pause.x = 508
    pause.y = 20
    sceneGroup:insert( pause )


    circle = {'c1','c2','c3','c4'}


    local function choice ( event )
        randCircle = circle[ math.random( #circle ) ]
        print(randCircle)
    end

    timer.performWithDelay( 3000, choice, 0 )

    local function tapListener( event )

    end

    c1 = display.newCircle( 75,100,75 )
    c1:setFillColor( 0,0,0 )
    sceneGroup:insert( c1 )
    c1:addEventListener( "tap", tapListener )

    c2 = display.newCircle( 300,100,75 )
    c2:setFillColor(0,0,0)
    sceneGroup:insert( c2 )
    c2:addEventListener( "tap", tapListener )

    c3 = display.newCircle( 187.5,225,75 )
    c3:setFillColor(0,0,0)
    sceneGroup:insert( c3 )
    c3:addEventListener( "tap", tapListener )

    c4 = display.newCircle( 412.5,225,75 )
    c4:setFillColor(0,0,0)
    sceneGroup:insert( c4 )
    c4:addEventListener( "tap", tapListener )

end


-- "scene:show()"
function scene:show( event )

    local sceneGroup = self.view
    local phase = event.phase

    if ( phase == "will" ) then

    elseif ( phase == "did" ) then

    end
end


-- "scene:hide()"
function scene:hide( event )

    local sceneGroup = self.view
    local phase = event.phase

    if ( phase == "will" ) then

    elseif ( phase == "did" ) then

    end
end


-- "scene:destroy()"
function scene:destroy( event )

    local sceneGroup = self.view

end


-- Listener setup
scene:addEventListener( "create", scene )
scene:addEventListener( "show", scene )
scene:addEventListener( "hide", scene )
scene:addEventListener( "destroy", scene )

return scene

Solution

  • You need the actual objects, not strings:

    circle = {c1, c2, c3 ,c4}
    

    This line should be executed after the circles are created.

    Before defining choice, add

    local circle