Let’s talk about the game;
Our code goes between hello, I feel like I am in a hamburger and the script hamburger goes between <body>..</body>. It is better to put it at the end of the body so that it loads after the website loads, otherwise our website will look slow.
- I have defined an array called “colors” with the color elements.
- I have defined Math.random to get a random number which return a number between 0 and 1, in other way [0,1). And then I multiplied it with the length of the array so that the range become [0,10). To find the length of the colors array I used colors.length. at the end that I used Math.floor to floor the random number because it will return a float number, such as 2,322232. Math.floor(2,322232) will convert this number to 2.
- Then I assigned the colors[randomNum] to a variable called chosen. Now in our chosen box we are carrying a random color from the colors array.
- prompt(“asdasda?”); is asking the user something and want the user to enter an input. And I assigned that input to guessed. This will be color that the user will guess.
5. Then with colors.indexOf(guessed) , we can find the box number of the guessed element from the colors array. You can think of box number as index of it, but don’t forget that in array box numbering starts with zero not one.
6. Here we have a while loop, it will run while the guessed and the chosen colors are not same and when the while the guessed color is in the array that we listed the colors. the statement guessedIndex != chosenIndex and guessedIndex > -1, both has to be true to make the statement true. It comes from true table, Boolean algebra. If any of them is false, the statement will be false, and the while loop will not work.
7. In the while loop we have if-else statement to check the guessed colors alphabetical order is lower or higher than the chosen color. This way, the player will find the color easily, and more interactive. askAgainBig() and askAgainSmall() are function that will run according to the input that user gives.
8. Here are the functions; askAgainBig() function will run when the input color’s alphabetical order is lower then the chosen color, so it asks the user to input another color that’s alphabatical order is higher (the first letter of the color). askAgainSmall() will run if the case is inverse of the above case. And the last function which is bgColor(color) runs when the true color is guessed and turns the background of the website into that color. This function runs when the game is won.
Looking forward to see you again,