HTML and CSS Reference
In-Depth Information
supports one-dimensional arrays. The facts array is one-dimensional. The facts[0] element is itself an
array, and so on.
Note: If the knowledge base was much more complex or if I were sharing the information or
accessing it from somewhere else, I might need to use something other than an array of arrays. I
could also store the knowledge base separate from the HTML document, perhaps using an eXtended
Markup Language (XML) file. JavaScript has functions for reading in and accessing XML.
The design for the quiz is to present a randomly chosen set of four facts for each game, so we define a
variable nq (standing for number in a quiz) to be 4. This never changes, but making it a variable means that
if we wanted to change it, it would be easy to do.
The HTML thats created dynamically (see next section) will take up two columns on the screen, with the
countries in the left column and the capitals in the right. I don't want the pairs to line up, so I use the
Math.random facility to position the capitals in the nq different positions. I think of these as slots. The
logic, presented here in pseudo-code, is the following
Make a random choice, from 0 to facts.length. If this fact has been used, try again
Mark this choice as used.
Create new HTML to be a block for the country and place in the next
position on the left.
Make a random choice, 0 to 3, to determine the slot for the capital.
If this slot has been taken, try again.
Mark this slot as used.
So how do we code this? As indicated earlier, the fact array contains arrays and the third element of the
inner arrays is a Boolean variable. Initially, these values will each be false, meaning the elements havent
yet been used in the game. After a time, of course, some facts will have been used, so I use another type
of loop, a do-while construct that will keep trying until it comes to a fact that hasnt been used:
do {c = Math.floor(Math.random()*facts.length);}
while (facts[c][2]==true)
The do-while exits as soon as facts[c][2] is false, that is, when the element at index c is available for
use.
We use similar coding to determine the slot for the capital. We define an array called slots . Now, we could
have made the values in the slots array Booleans, but instead were going to store the value c that holds
the index in the facts array once the code determines what that value is. For an initial value for each
element of slots , well use an arbitrary value of -100. The used values are in the range 0 to 19
( facts.length ). The coding is:
do {s = Math.floor(Math.random()*nq);}
while (slots[s]>=0)
slots[s]=c;
Creating HTML during program execution
An HTML document typically consists of the text and markup you include when you initially write the
document. However, you can also add to the document while the file is being interpreted by the browser,
 
Search WWH ::




Custom Search