HTML and CSS Reference
In-Depth Information
Code
Explanation
</body>
Closing body tag
</html>
Closing html tag
Combining the Date function with localStorage lets you do many things. For example, you can calculate
the elapsed time between a players current and last use of the application or, perhaps, the player winning
two games. In Chapter 5, we used Date to compute the elapsed time using the getTime method. Recall
that getTime stores the number of milliseconds from January 1 , 1970. You can convert that value to a
string, store it, and then when you fetch it back, do arithmetic to calculate elapsed time.
The localStorage key/value pairs last until they are removed, unlike JavaScript cookies, for which you can
set a duration.
Encoding data for local storage
For simplicitys sake, the first application consists of just one HTML document. You can use this version
to create mazes, store and retrieve them, and move the token through the maze. The second version of
the application involves two HTML documents. One script is the same as the first application and can be
used for building, traversing, and saving mazes as well as traveling each maze. The second script is just
for traveling one of a fixed list of saved mazes. A set of radio buttons allows the player to pick from easy,
moderate, and hard options, assuming someone has created and saved mazes with the names
easymaze , moderatemaze , and hardmaze . These names can be anything you want and as many as you
want. You just need to be consistent between what you create in one program and what you reference in
the second program.
Now let's address the issue that localStorage just stores character strings. The applications described
here must store enough information about the walls so that these walls can be added to the canvas. In the
one-document version, the old walls are actually added to whatever is on the canvas. The two-document
version erases any old maze and loads the requested one. I use two forms, each with an input field for the
name and a submit button. The player chooses the name for saving a maze and must remember it for
retrieving.
The data to be stored is a character string, that is, a piece of text. We will create the text holding the
information for a set of walls by doing the following for each wall:
Combine the sx, sy, fx, fy into an array called w for a single wall.
Using the join method, use the w array to generate a string separated by + signs.
Add each of these strings to an array called allw , for all the walls.
Using the join method again, use the allw array to produce a string called sw .
The sw string variable will hold all the coordinates (four numbers for each wall) for all the walls. The next
step is to use the localStorage.setItem method to store sw under the name given by the player. We do
this using the try and catch construction explained in the last section.
try {
localStorage.setItem(lsname,sw);
}
 
Search WWH ::




Custom Search