In this game, a RGB value will be generated randomly and player will need to select the correct colour based on the RGB value.
Label, Horizontal Arrangement, Button, Notifier
In this project, we will break our code into two main functions:
generateQuestion – This function will generate the RGB values for the answer options, a random index as the correct answer, and the string for questionLabel
updateUI – This function will update the mobile app UI
When the main screen initialised, call the generateQuestion and updateUI functions
First, generate a number randomly between 1 to 3 and store it into the answer variable. This number will be the index of the correct answer.
Next, create a variable buttonColours to store the RGB values for all three buttons. Each RGB value is saved as a list with three numbers between 0 and 255, representing the intensity of red, green, and blue respectively. Essentially, buttonColours is a list with three lists.
Create a for loop that counts from 1 to 3. In each loop, generate an RGB value and push it into buttonColours. If the loop variable is equal to answer, generate a string with the RGB value and store it into the question variable.
In updateUI function, update the background colour of all three buttons based on the value stored in buttonColours and the value of QuestionLabel.
Create a function checkAnswer to check if a user clicked the correct button. The checkAnswer takes a parameter and the argument is the index of button clicked. When the function is called, we first check if the clicked button index equals answer. If so, update the score. Else, reset the score to zero and display a dialog notifying the user the game is over. Next, call the generateQuestion and updateUI functions to start the next question. Finally, update the score label to display the latest score.