๐ Building JavaScript Programs
Building a program is a process of evaluating the requirements of a client to determine how a computer can perform a desired function. A lot of students struggling with this process. Iโm going to try to explain some of the concepts here.
Control Structures
Control structures are a category of coding techniques that provide the capability for a programmer to instruct the computer how to carry out the process to achieve the desired result. There are only a couple of needs but several methods of achieving the results.
Conditionals
To control the program, we'll be using conditional statements to evaluate the data. The data in this case will be the user input and some predetermined values stored in the program.
Loops
We will also want a reliable way to perform repetitive tasks like collecting user responses. If our program has more than one item it needs from the user, we might want to use a loop to request the input in a series of requests. To do this, we'll use loops to repeat these tasks.
User Input
You will also need a way to capture user input if you want your program to interact with the user. For example, you will need a way to collect information from the user. This might be in the form of a prompt box requesting user input or a form with form fields the user is filling. With JavaScript we will also see in future lessons that we can monitor user inputs through mouse movements and clicks. For now, we'll just use a basic prompt();
statement to interact and collect the needed information.
The Requirements
The assignment instructs you to create a quiz game where you are to prompt your visitors to answer three questions and check their responses against a predetermined โcorrectโ answer. Each time the visitor responds they have an opportunity to acquire points for a correct response. The points diminish for each attempt. The first attempt, the points are 3, second attempt 2 points and the third attempt only 1 point. If they miss after three tries, they donโt get any points and the next question is provided.
Unpacking the Needs
- From the requirements you should see that we will need a way to interact with the user to provide them three trivia questions and collect their responses. The JavaScript prompt(); statement will work well for this.
- We will also have predetermined questions and answers. We can use JavaScript arrays to hold the questions and answers for later comparison.
- We will need to evaluate each response to determine if it is a "correct" answer by comparing the user input to the programmed answer. JavaScript conditional statements work well for this.
- If the user response (guess) is wrong, we will need to keep prompting the user to try again. This repetitive task will need a loop to manage the repeated prompting.
- The user has three questions in addition to three guesses for each question. This will reauire a second loop to track the questions as they are provided to the user.
Setting up the question and answer arrays.
We have a lot going on here, but a couple of easy things to prepare. First, we can create the arrays needed for the quiz. We can have one question array and a second separate answer array that uses matching indexes. See this example.
// set up question and matching answer arrays
var mathQuest = ['3 + 2', '7 - 4', '10 / 5', '6 X 2'];
var mathAns = ['5', '3', '2', '12'];
Remember, you are building a trivia game, not a math quiz game. Your arrays should have trivia questions that are easy to guess for most people. Asking how many flies buzz around the average burro in Lithuania is not a good trivia question. Asking how many moons orbit the Earth is much better. You're not trying to make the game difficult. You're trying to make it work.
Evaluating the visitor's response.
In the arrays above, mathQuest has 4 items. The first item has an index number 0 as defined by JavaScript. This is typical of programming languages to use 0 as the first numeric index of an array. So, mathQuest[0] has the value of '3 + 2'. Also, mathAns[0] has the value of '5'. If we prompt the user with a "math question" of "What is 3 + 2?" We could then capture the user input and compare it to the mathAns of 5 to see if the user entered a "correct" answer. If they did, we award the points and alert them that they were correct. If they are wrong we alert the user and award no points.
// prompt user with math question
ans = prompt("What is " + mathQuest[0]);
// see if the answer matches the answer array
if (ans == mathAns[0]) {
// if correct, add 1 to points and alert user
points = points + 1;
alert("Correct!");
} else {
// if answer doesn't match alert user
alert("Incorrect");
} // end if
Providing visitor feedback.
This is a good start but we need to be able to respond to a user input that is wrong and send the question back to the user up to three time if they keep getting it wrong. So next, we will add a counter to the else part of the conditional to decrement the counter and wrap the whole thing in a while loop to repeat the question as many times as the user needs, up to three.
//set attempts to 3
var attempts = 3;
// use a while loop to give the user 3 attempts to answer
while (attempts > 0) { // if attempts equals 0 the while loop ends
// prompt user with math question
ans = prompt("What is " + mathQuest[0]);
// see if the answer matches the answer array
if (ans == mathAns[0]) {
// if correct, add 1 to points, alert user and set attempts to 0
points = points + 1;
alert("Correct!");
attempts = 0; // setting the attempts to 0 will end the while loop
} else {
// if answer doesn't match, alert user and subtract 1 from attempts
alert("Incorrect");
attempts = attempts - 1;
} // end if
} // end while
Tracking the game play.
The last thing we need to do is create a way to have all the questions shown to the user in succession as the game proceeds. We provide the first question and wait for it to resolve, then we repeat the process with the second question and so on until all the questions have been asked and answered. All we nee to do is take the game we have and wrap it in another loop that will control the interaction of providing the questions to the user. A for loop is a good choice. We can set the initial index to 0 to correspond with the array index of the first question and answer. We can also run the loop until all questions have been asked. While we're at it, we'll need to track the number of points earned by the user. Here's how.
// initialize points
var points = 0;
//use a for loop to loop through each math question
for (var i = 0; i <= 3; i++) {
//set attempts to 3
var attempts = 3;
// use a while loop to give the user 3 attempts to answer
while (attempts > 0) {
// prompt user with math question
ans = prompt("What is " + mathQuest[i]);
// see if the answer matches the answer array
if (ans == mathAns[i]) {
// if correct, add 1 to points, alert user and set attempts to 0
points = points + 1;
alert("Correct!");
attempts = 0;
} else {
// if answer doesn't match, alert user and subtract 1 from attempts
alert("Incorrect");
attempts = attempts - 1;
} // end if
} // end while
} // end for
A couple of things happening here. The first you should know is we are using the var i as the index for the loop and the array. This is by design. We use that number to get the correct item from the array using the value of var i as the index number. When the loop initializes, var i will have a value of 0 allowing us to access the first item in both arrays using mathQuest[i];
and mathAns[i];
respectively. The other thing you should notice is we set the value of points to 0 initially and increment the points for each correct answer. This game allows a single point for any correct answer. Your assignment uses a point structure that changes based on user attempts.
Running the Program
Now that you have code that works, you'll need some way of running it in your application. To run a JavaScript application it helps if you have a good way to call the program at run time. The easiest way to do this is to wrap the program we've built in a function and then just call the function when we're ready. This takes two parts. The first part is to wrap the game in a function inside the JavaScript file and the second part is to call the function in the HTML file.
JavaScript File Contents
// set up question and matching answer arrays
var mathQuest = ['3 + 2', '7 - 4', '10 / 5', '6 X 2'];
var mathAns = ['5', '3', '2', '12'];
// math quiz function displays math questions and gives the user 2 attempts to get it right - then returns a score
function mathQuiz() {
// initialize points
var points = 0;
//use a for loop to loop through each math question
for (i = 0; i <= 3; i++) {
//set attempts to 3
var attempts = 3;
// use a while loop to give the user 3 attempts to answer
while (attempts > 0) {
// prompt user with math question
ans = prompt("What is " + mathQuest[i]);
// see if the answer matches the answer array
if (ans == mathAns[i]) {
// if correct, add 1 to points, alert user and set attempts to 0
points = points + 1;
alert("Correct!");
attempts = 0;
} else {
// if answer doesn't match, alert user and subtract 1 from attempts
alert("Incorrect");
attempts = attempts - 1;
} // end if
} // end while
} // end for
// return the points variable
return points;
} // end mathQuiz function
Partial HTML File Contents
<!-- usually placed in the header of the HTML file to call the external JavaScript file -->
<script src="math-quiz.js"></script>
<!-- must be placed in the body of the HTML file where you want the contents to display -->
<script>
// call mathQuiz function
var score = mathQuiz();
// display the results on the screen
document.write('Your score is ' + score);
</script>
An Alternate Implementation
There is another way to deploy this application that works a little different. You could wrap the part of the application code that deals with one question in a function and then call the function inside a for loop while passing the index (i) to the function. This would still allow the use of the for loop index to control the array question and answer access but might allow a different implementation of the application. Here's the code do do that.
JavaScript File Contents
// set up question and matching answer arrays
var mathQuest = ['3 + 2', '7 - 4', '10 / 5', '6 X 2'];
var mathAns = ['5', '3', '2', '12'];
// initialize points
var points = 0;
//use a for loop to loop through each math question
for (i = 0; i <= 3; i++) {
var score = mathQuiz(i);
} // end for
// math quiz function displays math questions and gives the user 2 attempts to get it right - then returns a score
function mathQuiz(i) {
//set attempts to 3
var attempts = 3;
// use a while loop to give the user 3 attempts to answer
while (attempts > 0) {
// prompt user with math question
ans = prompt("What is " + mathQuest[i]);
// see if the answer matches the answer array
if (ans == mathAns[i]) {
// if correct, add 1 to points, alert user and set attempts to 0
points = points + 1;
alert("Correct!");
attempts = 0;
} else {
// if answer doesn't match, alert user and subtract 1 from attempts
alert("Incorrect");
attempts = attempts - 1;
} // end if
} // end while
// return the points variable
return points;
} // end mathQuiz function
Partial HTML File Contents
<!-- usually placed in the header of the HTML file to call the external JavaScript file -->
<script src="math-quiz.js"></script>
<!-- must be placed in the body of the HTML file where you want the contents to display -->
<script>
// display the results on the screen
document.write('Your score is ' + score);
</script>
Finishing Up
There isn't a lot of difference between the programs. Choosing one over the other would depend on the implementation specifications. It would be up to the developer to decide.
You already have examples of how to create and use arrays, how to create and use while and for loops and how to use if/else statements to make comparisons of data values. These are the tools we need for this assignment. You now have a coded example of the mathQuiz that is very close to what you need for the Trivia Quiz.
Begin with the mathQuiz example code. Change the arrays to match your needs (trivia questions). Make sure you add the attempts to the points as we are awarding points based on how many tries it takes. To see a working example of the Math Quiz, go to https://2learnweb.brookhavencollege.edu/profherd/javascript/examples/math-quiz-example/math-quiz.html.
That should do it. Try your code periodically so you can see what each change does.