In: Computer Science
-create a magic 8 ball program in Javascript.
-use a loop to ask for the question
-use a random number to get the answer let randAnswer =
Math.round(Math.random()*10);
-must have at least10 different answers
-must use elseif or switch statement
-must outputs both answers and user to input the console
-program should repeat indefinitely until either blank input or
cancel is selected
Complete Code:
<html>
<head>
<script>
<!-- JavaScript code -->
var responses = ['Please ask again later...', 'Yes', 'No','It
appears to be so','Yes, definitely','What is it you really want to
know?', 'My sources say no','Signs point to yes', 'Don\'t count on
it', 'Can`t predict now']; <!-- different responses to
questions-->
var repeated; <!-- to check if question is repeated -->
function change()
{
var ques = document.getElementById('ques_id').value; <!-- to
store question -->
if(ques.endsWith("?")) <!-- check whether question ends with a
question mark (?) or not -->
{
if(repeated==ques) <!-- compare current question with the
previous question -->
{
alert("Please ask different question..");
}
else
{
var rand = responses[Math.round(Math.random() * responses.length)];
<!-- generate response using random function -->
document.getElementById('ans_id').innerHTML = rand; <!-- set
answer -->
repeated = ques; <!-- question -->
}
}
else
alert("Please enter a question with mark '?'"); <!-- input
question-->
}
</script>
</head>
<body>
<center>
<h1>Magic 8 Ball</h1>
<h4>What would you like to know?</h4>
<textarea rows="1" cols="50"
id=ques_id></textarea></br></br>
<input onclick="change()" type="button" value="Ask the 8 Ball"
id=myButton1"></input>
<h4>The 8 Ball says :</h4>
<i><p id="ans_id">Ask the 8 Ball a
question...</p></i>
</center>
</body>
</html>
OUTPUT: