This is in Java script. Write a program that randomly chooses any of the 5 colou
ID: 3879047 • Letter: T
Question
This is in Java script. Write a program that randomly chooses any of the 5 colours below. ( can choose same color more than once)
Yellow Blue Orange Red Green. For the program to randomly choose a colour it can generate a random number.
For example 0 can represent green and 1 yellow and so forth.
The program will choose a random color and ask the user to guess the color. After the guess it will reveal the color it chose.
Let the program repeat 10 times. It should then display how many times the user was able to correctly guess the color.
Make sure to modularize the program separating the methods that perform each of the main task.
Explanation / Answer
function main(){
// set guessCount to zero
var guessCount = 0;
for(var i=0;i<10;i++){
color = getRandomColor();
// get color from user
var guess = prompt("Enter a color:");
// check if color and guess is equal
if(color == guess){
guessCount += 1;
}
}
document.write("You guessed color correctly " + String(guessCount) + " Times");
}
// get a random color from list
function getRandomColor(){
// define colors list
var colors = ["Yellow","Blue", "Orange", "Red", "Green"];
// generate random number between 0,4
var rand = Math.floor(Math.random() * 4);
return colors[rand];
}
main();
/*
sample output
You guessed color correctly 4 Times
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.