Before you keep reading...
Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.
Before you keep reading...
Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.
Selection allows us to ask questions, and take different actions depending on the answers. We use selection every day as we go about our duties. If it’s cold out we put on some extra clothes. If it’s raining we grab our umbrella before we leave the house. These are examples of the kinds of decisions we make. More formally we can put this into an
if it is raining,
then we take our umbrella.
a text box to make sure that it is a good value. For example if colors can only be in the range from 0 to 255 we could check the value of an input box as follows:
In this example we have one function that can check the values for any of our color text input boxes. Once again we have the interesting issue of how does the checkme function know which text box it is supposed to check? When we are setting up a call from html we can pass
this as a special parameter that refers to the object that the onchange is connected to.
If you want to get a little practice, add another if statement to
checkme that ensures the value entered by the user is greater than or equal to zero.
5.9. Guessing Game¶
Here is a simple application that uses selection to allow you play the old guessing game.
The computer will select a number between 1 and 100. You can type in your guess into the box and the computer will tell you when you are right, or if your guess is too high or too low.
Math.random() It generates a random number between 0 and 1, so we’ll have to do a little bit of work to turn that into a random number between 1 and 100.
Things to do:
Change this to not use an alert. Update the innerHTML of a paragraph to tell the user if they are too high or too low.
Add a dynamically created list to keep track of the guesses, color the guesses that are too high red, and the guesses that are too low blow.
Keep track of the number of guesses and tell the user at the end how many guesses they needed.
To play a new game, you must now reload the page. Can you add a reset button that makes up a new number and clears out everything else?