We are ready to create our magic 8-ball method now. In this challenge, we are going back to the magic 8-ball object we created and adding to it the method you will use to make it work just like a magic 8-ball. You will write pseudocode for your method just like the one we just wrote for the chair method we did in the last challenge. By the end of this challenge, you will have a method and a call to get your method to run.
Solution
Let’s get started by setting up the function pseudocode. Underneath your magic 8-ball object, you will want to add the function keyword. Then you will want to name your method.
I’m going to name the one in this example ask question but you can use anything you like for yours. In the next line, we will put the stop keyword at the end of our method. Now it is time to write the instructions.
First, we need to get a question from the user. So the first line in the instruction will be the inputs. Put an input keyword then a question.
This lets the computer know the user needs to give it a question to start working. Once the user has given a question, it is time for the magic 8 ball to start working. The second step will be where the magic 8 ball shakes.
Underneath the inputs step, I will put that the 8 ball is shaking. The Magic 8 ball now needs to go through the list of answers and randomly pick one to show the user. The 8 ball can’t automatically pick an answer to give the user.
It needs a list of answers to reference and pick from to decide what to display. After the second step, I will put a line that says the 8-ball picks an answer from the list of answers. We are in the home stretch with this method.
The last thing we need to include inside the method is the output. The output in this method is the answer the computer had picked. Before the stop keyword, I’m going to add the output keyword and then answer.
This lets the computer know they need to show the user the answer. The method is done. The last thing we need to do is call our method.
Underneath the method, I’m going to call my method using the run function keywords. I call my method using the ask question name. Then I will use the with keyword before I list my parameter value.
This value is a yes/no question I can ask the computer. In this example, I am using the question “Will I ever learn JavaScript?” but you can use any question you like for your magic 8 ball.
Finished Pseudocode
Congratulations! The magic 8-ball method is finally finished and ready for when you start writing JavaScript code later in this course. Here is a look at the finished pseudocode I created for this example. Don’t forget to indent your instructions inside your method.
OBJECT Magic 8-Ball
PROPERTY list of answers
FUNCTION ask question
INPUT question
8-ball shakes
8-ball picks random answer from list of answers
OUTPUT answer
STOP
RUN FUNCTION ask question WITH INPUT "Will I ever learn JavaScript?"