C. wants to make a computer program be to be like the Magic 8 ball, in my last post, I couldn’t remember how to generate a random number. But found it here

Math is a class (not an object ), it has 2 class member functions.

random()

which will give me a random decimal between 0 and 1, like 0.11, 0.34. If we take this and multiply by 6, then we will get a number between 0 and 6, but less than 6

floor()

will round off the decimal number to an integer.

Math.floor( Math.random() * 6)

So here is the program, which will magically give you an answer to any question you have in the word

<body>
var question = window.prompt("Ask a question! :)");
/* RFE: time thing change question after 5 secs, to ask the user to hurry up */
var magicAnswers = [
"Duh",
"Hazy, try again",
"No way",
"Awoooga",
"We'll see",
"Of course!",
"Yawn...",
"Yep."];
/* Math.random() the computer makes a random number between 0 and 1,
gives you answer to your question
multiply by 5 would give you a number between 0 and 4
Math.floor makes the number a round number
*/
var randAnswer = Math.floor(
Math.random()
*8)
window.alert("Q: " + question + "nn" + "A: "+ magicAnswers[randAnswer]);
</body>
/* the engine of the Magic 8 ball game is simple and complete, some ideas
for the UI
1) have a wizard stand behind a crystal ball, ask a question, zoom in to
the crystal ball and show the answer
2) have a bouncing black eight ball, ask a question and the eight ball
shakes a bit and shows the answer, it prompts you every 3-5 seconds.
As another enhacement, we can keep a history of all the previous
questions and answers. display the question a bubble next an avatar
of the person asking follow by the answer
almost like a comic strip
This will allow us to see the previous history of all the funny
question and answers
*/

## This is a series that documents my daughter’s curiosity to learn about computer programming

### Like this:

Like Loading...

*Related*