Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Solved How can I ensure both randomly generated colors are not the same?

    QML and Qt Quick
    qml qt quick
    3
    3
    240
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • N
      newbiSoso last edited by

      I'm making a simple game where two shapes change colors repeatedly using a timer, I have an array of colors to choose from how can I make sure both shapes will have be colored differently?

      My code:

      property variant colorArray: ["#008499","#963A65","#01FF97","#FF4140"] //colors to choose from
      Timer{
              id: color_switch
              interval: 1000; running: true; repeat: true
              onTriggered: {
                  shape1.color = colorArray[Math.floor(Math.random()*3)]
                  shape2.color = colorArray[Math.floor(Math.random()*3)]
              }
          }
      
      JonB 1 Reply Last reply Reply Quote 0
      • JonB
        JonB @newbiSoso last edited by JonB

        @newbisoso
        So in some shape or form you have to write a tiny bit of code there which checks: while the second call to Math.random() * 3 returns the same as the first call did, call it again!

        1 Reply Last reply Reply Quote 2
        • IntruderExcluder
          IntruderExcluder last edited by

          Just genereate 2nd index until it is not same as 1st index:

                  let idx1 = Math.floor(Math.random() * 3);
                  let idx2 = Math.floor(Math.random() * 3);
                  while (idx2 === idx1)
                      idx2 = Math.floor(Math.random() * 3);
          
          1 Reply Last reply Reply Quote 3
          • First post
            Last post