FIT100 Fluency with Information Technology

Project 2

Winter 2003

 

 

The goal of Project 2 is to introduce JavaScript, a programming language that allows the creation of active Web pages.  It is possible to create Web pages with animations, pages that perform computations, and pages that have “forms” type inputs, like surveys.  Project 2 will demonstrate several of these features.

Text Box: In all parts of Project 2 you must comment the HTML and JavaScript that you write or change. The comments do not have to be long, but they must say what you’ve done in a way that is coherent to a human.  Uncommented HTML and JavaScript will not be graded.

 

 


The ultimate goal of the project is to produce the Orange Concentrate application.

This is an ambitious project, so we do it in 4 parts. We begin first by a practice exercise in personalizing the Memory Bank application. Then in three more parts, we build the Orange Concentrate.  Each part will have a separate turn in, and there will be a version of the previous part available at the start of every later part.

 

The application works as follows.  The user clicks “New” to start a new concentration challenge. A set of n randomly chosen squares are filled in in the upper grid, the pattern grid. (The user can control n, which is initially 3.) This pattern remains displayed for s seconds, and then it disappears. (The user can control s, which is initially 5.) The user then keys in the same pattern in the mouse keys, the lower brown key grid. With each click on the key grid, the corresponding square above is set. When the user thinks the pattern is right, he or she clicks the check button. The matching positions are shown in purple, and the missed squares are shown in red.  If the user forgets the pattern and wants to see it again, clicking on “View” shows it again for s seconds. Finally, the marked squares can all be cleared using the “Clear” button. (The pattern is remembered.)

 

Project 2a Exercise

The purpose of part 2a is for you to get experience modifying and running JavaScript programs in order to become familiar the JavaScript programming process.  So, the task is to customize the Memory Bank program from Chapter 19 pp. 371-382. 

Read these pages before proceeding further. 

The source for that program can be found at www.aw.com/snyder/ and copied.  (Remember, you need to grab the GIF for the bullet mark, too.) Or, you can type in the code from Appendix D, pp. 463-465; but if you do, type it very carefully to avoid errors.

 

Your specific tasks are as follows (refer to the Memory Bank page).

 

A1. Change the Look.  Make some modification(s) to the “look” of the Memory Bank page. You can completely change it, or only slightly modify it by revising its background color, font, font color, etc. to your liking. The result should be attractive.  If you decide you like it the way it is, i.e. you plan no other changes, then you must change the level 1 heading to include your name. For example, I would change it to “Larry’s Memory Bank.”

 

A2.  Add a link to the Web page. Since JavaScript uses HTML, the links to remote pages are just HTML links, which you are already familiar with.  Change the links in the Memory Bank program so that they point to destinations of interest to you.

(a)    To the Reference links, add a link of personal interest, or a link to www.google.com/advanced_search?hl=en (or both).

(b)   Change the Classes entries to match your classes, i.e. make some link suitable for each of your classes this term.

(c)    Add one more category of links of your choice, say, links to friends, links to news, or a Hot-List of favorite sites.

 

A3. Good as Gold.  Add a new computation line to the Memory Bank page. Your computation can be one of your own choosing, or it can be the following computation to convert a weight to gold, or both. (On January 28, gold was trading for $368.40 per troy ounce, of which there are 12 per pound.) Therefore, the computation is

 

Worth = (Weight*12)*368.4

 

 

Using the analogy of the Celsius to Fahrenheit computation that already exists on the Memory Bank page,

(a)    Create a new row in Memory Bank with the proper title (left side table data).

(b)   For the right hand side table data, construct the text input window. Begin with the text “Weight LBS”, and then place the input window, giving it a unique name and a size of 3.

(c)    Construct the text input window (for output). Place the text “Worth As Gold $”, and then place the window, giving it a unique name, and a size of 7.

(d)   Construct a function – place it with the other functions -- named worthau(), and having one parameter. The function worthau() returns the dollar value of a given weight (in lbs) of gold.

(e)    Define the onChange event handler for the input control of (b) to assign the result of the worthau() function applied to the input value from (b) to the output window of (c). (Notice how this is achieved in Celsius to Fahrenheit.)

(f)     Include the following “last modified” code on your page at the bottom.  (If the position where you place this code is already inside JavaScript tags, you do not need those shown.):

 

<script language = "JavaScript">

var _modified;

document.write("Last Modified: ");

modified = document.lastModified;

document.write(modified);

</script>

 

Hint: Part A3 is extremely easy if you have studied and understood the Celsius to Fahrenheit computation.

 

A4.  Turn In.  Publish your new Memory Bank page in your Web space under a unique name. (Your Memory Bank page is for your use, not for public use, so choose a name that is memorable to you.)  Remember to include the bullet.gif.

(a)    Have your Memory Bank page published by 2:00 AM, Monday, Feb. 10, 2003.

(b)   Do not modify your page until after it is graded.

(c)    Send an email message to your TA giving the URL for your page.

(d)   Print the HTML/JavaScript source, add your name, address and section number, and turn it in in class.

Text Box: In all parts of Project 2 you must comment the HTML and JavaScript that you write or change. The comments do not have to be long, but they must say what you’ve done in a way that is coherent to a human.  Uncommented HTML and JavaScript will not be graded.

 

 


Project 2b Key Sensing

 

The purpose of Part 2B is to begin creating parts for the Orange Concentrate application, Part 2D.  Part 2B builds an array of mouse-activated “keys.”  The “keys” are actually tiny GIF images, and as the mouse moves over them, they change color.  The page has the form

Notice that the cursor (not visible) is over the square in the lower right corner, causing it to change color from brown to orange.  All keys change to orange while the mouse is over them. When the mouse moves elsewhere, they return to the basic brown color.

 

This part depends on your knowing “Prefetching Images” and “Redrawing Images,” (pp. 401-402) of Chapter 20, and “Key Sensing Task” (pp. 418-420) of Chapter 21. The following explanation assumes you’re familiar with that reading.

 

B1. Initial Page.  Set up a new Web page to host key sensing.  It must include a title with your name in it, and the other basic HTML including script tags.  Begin with a heading saying “Mouse Sensing”.

 

B2. Grab the GIFs. Retrieve the six .gif files to your desktop by right-clicking on the images, using the operation, Save Image As… .

          

You will only use three of these GIFs (BrownBox.gif, OrangeBox.gif and RedBox.gif) for Part B, but you will use them all by the end of the project. So, get them now, and to simplify your life, keep them in this order.

 

B3. Prefetch the GIFs. Step B2 only got the GIFs to your computer so you can work on the project.  The Web page (from B1) must also get the files for its use.  This is called prefetching the files, and is done so that the time to transmit them over the Web doesn’t cause delay in the application.

 

As explained in Prefetching Images, it is necessary to declare an array to hold the fetched images.  You need an array with as many elements as images, that is, six.  The array elements must be initialized to be new Images.  And then, the GIFs must be assigned to the array elements.  You will perform the following steps:

a)      Declare an array variable with a unique name of your choice; declare an index variable, such as i.

b)      Write a loop – use the World Famous Iteration – to initialize the array elements to new Image.

c)      Assign the GIF elements you will be using to the .src field of the image array.  Notice that you cannot use a loop for this because the GIFs all have different names.  Assign BrownBox.gif, OrangeBox.gif and RedBox.gif to the first three elements in that order.

 

B4.  Test Your Step B3.  Place three image tags before your <script> tag:

 

<img src="BrownBox.gif">

<img src="OrangeBox.gif">

<img src="RedBox.gif"><br>

 

and display the page. You should see the three squares in the order Brown, Orange, Red.  If not, something is wrong with Step B3 or your test. 

After you’re sure that this is working, add commands like the following code at the end of your JavaScript code INSIDE the script tags. Your code will be different because it will fill in your array name – don’t take <yourArrayName> literally.  [You chose a unique name in step B3a.] Everything else will be the same, especially the indices.

 

document.images[0].src=<yourArrayName>[1].src;

document.images[1].src=<yourArrayName>[2].src;

document.images[2].src=<yourArrayName>[0].src;

 

Now reload the page. You should see the squares in a different order, namely, Orange, Red and Brown.  (Notice, if you don’t load the GIFs in the order indicated (Step B3c) or don’t list the <img src…> tags as given, or don’t reload the document.images in the order shown, then your display will be different.  But the order doesn’t matter as long as you’re sure you did the steps of B3 right.)   What you are doing in the test is placing the three GIFs on the page in one order, and then overwriting them using the document.images assignments to change them.  It is a way to see what is happening in your JavaScript program, since to this point there is nothing else to see.

 

Remove the image tags and the document.images assignments that you inserted for testing.

 

B5.  Place a Row of Mouse Keys.  Instead of the three image tags you just used for testing, you will now create a row of seven image tags. But instead of writing them down literally, you will place them into your page using a loop and document.write inside the <script> tags. (This is illustrated at the top of page 419.)  Perform the following steps.

a)      Write a WFI that iterates seven times using the iteration variable of B3a.

b)      On each iteration place an image tag for the BrownBox.gif using document.write.  (The “incomplete” formulation of p. 419 is OK at this point.) 

c)      After the loop place a <br> tag using document.write.  This moves the HTML cursor to the next line.

Check that your seven boxes appear on your page in a tight horizontal row.

If there are spaces between the GIFs then you may be writing a space before or after the GIFs in step (b).

 

B6.  Make a Grid of Keys.  The loop from step B5 will now become the body of another loop, i.e. the statement iterated by an enclosing loop. (Figure 20.1 shows one loop enclosed by another.)  The result of this double loop is a “stack” of seven rows each with seven GIFs, that is, a 7x7 grid of BrownBox GIFs.

 

 

Writing this loop will be straightforward. Perform the following operations.

a)      Declare another variable, say j, for the outer loop.

b)      Before the loop of step B5 place the outer loop’s components up to and including the open brace({),  iterating seven times on the variable from(a).

c)      Following the loop of B5 place the closing brace (}) of the outer loop.

These last two steps cause the row construction of B5 to be repeated seven times, creating the grid. Check your result.

 

B7.  Include Event Handlers for the GIFs.  For the grid of GIFs to become mouse keys, we must add event handlers to each of the images placed in B5.  (Recall that that formulation was incomplete.)   The event handlers will tell the browser what it is to do when the mouse is over a GIF or is clicked on a GIF. Three events are possible:

MouseOver is the event of a mouse being over a GIF,

MouseOut is the event of a mouse, having previously been over a GIF, to move somewhere else

Click is the event of a mouse button being clicked on the GIF.

We will use event handlers named here(row, col) for the onMouseOver event, gone(row, col) for the onMouseOut event, and fire(row, col) for the onClick event.  Notice that all three need to know the position of the GIF in the 2 dimensional grid of GIFs.  The row is the number of rows down from the top, 0-origin indexing, and col is the number of columns from left, 0-origin.  (Thus, the colored box at the start of this part is row=6, col=6.)

 

Following the strategy on p. 420, REVISE the document.write of B5b to include the event handlers.  (On p. 420 two event handlers are included with just one parameter; you will have three event handlers (here(), gone() and fire()), each with two parameters.) The two parameters will be the iteration variables of the two loops – row will be the iteration variable from the outer loop, col the iteration variable from the inner loop. Coding the string for the document.write is intricate because you have to get the quotes to match.

 

Check to see that you still create the page of the last step. (If you mess up the quotes, the busted page will reveal where you messed up.)

 

B8. Create Event Handlers.  The three event handlers – here(), gone() and fire() – are all alike in that they simply change the GIF value as was done in the check for B4 from its current value to a new value stored in the image array. That is, each procedure will be called with the two parameters, row and col, and it must change the image in the document.images list.  The document.images is an array of elements numbered 0 to 48, and the position in that sequence for the GIF in (row, col) is the row*7+col element. The changes are

a)      here() changes document.images[row*7+col].src from (the current) brown box to an orange box, that is OrangeBox.gif, which is stored in <yourArrayName>[1] in step B3.

b)      gone() changes document.images[row*7+col].src from (the current) orange or red box to brown, that is BrownBox.gif, which you stored in <yourArrayName>[0] in step B3.

c)      fire() changes document.images[row*7+col].src from (the current) orange box to red, that is RedBox.gif, which you stored in <yourArrayName>[2] in step B3.

The functions do not have to return any value. Their whole operation is to make the assignment to update document.images from the prefetched GIFs.

 

Testing your solution, you should be able to move the mouse over the grid and the squares change color as the mouse moves over them.  When one is clicked, it should turn red until the mouse moves off of it. 

 

B9.  Turn In.  Publish your new page in your Web space under a unique name.  

a)      Have your Mouse Sensing page published by 2:00 AM, Wednesday, Feb. 19, 2003.

b)      Do not modify your page until after it is graded.

c)      Send an email message to your TA giving the URL for your page.

d)      Print the HTML/JavaScript source, add your name, address and section number, and turn it in in class.

 

 

Text Box: In all parts of Project 2 you must comment the HTML and JavaScript that you write or change. The comments do not have to be long, but they must say what you’ve done in a way that is coherent to a human.  Uncommented HTML and JavaScript will not be graded.

 

 


Project 2c Pattern Fill

 

The goal of part 2C is to extend the Mouse Sensing page to set squares in the pattern window.  The result has the form

where two squares have been clicked and the mouse (not visible) is over the square in the lower right corner of the key grid about to click a third square position.  Note the clear button.

 

Overall, the task is quite similar to 2B, since it involves constructing a GIF array and setting positions from white to blue.  The main difference is that the mouse doesn’t activate the pattern array. You need to take the following steps.

 

C1. Create a new page. Make a copy of the working version of Part 2B. (A copy is available here.)  Change the heading to reflect the new task of Pattern Fill.

 

C2.  Construct the Pattern Grid.  Recall how the key grid was constructed using Steps B5 and B6.  Before the key grid, construct a doubly nested loop to place a 7x7 grid of WhiteBox.gif images using document.write. These will not have any event handlers, so the task is simply to place the <img src…> tags, and after every seven images the <br> tags.  Verify that the pattern grid is well formed.

 

C3. Fix the Key Grid.  When you inserted 49 images (the pattern grid) in front of the key grid in C2 you changed the positions of the GIFs of the key grid in the document.images array. The images are listed in the order that the browser encounters them on the page, and the pattern grid occurs before the key grid.  The key grid images are now 49 positions further down the list.  The main affect of this is that the event handlers refer to the wrong images.  They presently refer to row*7+col, and now have to refer to 49+row*7+col. Change each of the three event handlers – here(), gone() and fire() – so that the index position of document.images is 49 larger.  Check that the key grid is working again.

 

C4.  Set Pattern Grid on A Click.  When a key grid square is clicked, the corresponding position in the pattern grid should be set to a blue box.  The blue box is BlueBox.gif, which was prefetched and (probably) stored in index position 4 of the images array.  Add a second statement to the fire() event handler so that in addition to setting the key grid position red, it sets the corresponding pattern grid position blue.  “Corresponding” means 49 positions earlier, of course.  Check that the code works.

 

C5.  Place the Clear Button.  Define a form following the </script> tag. (Multiple examples of this construction are shown in Chapters 18, 19 and 21. The form should have a unique name of your choice, and it should have a matching </form>.  Inside the form, add a button input with the value “Clear” and make its onClick event handler call the function whiteout().

 

C6.  Write the whiteout() Function.  The whiteout() event handler clears all of the positions on the Pattern Grid. That is, it sets the first 49 images in document.images array to WhiteBox.gif, which was prefetched in the Part 2B and is (probably) stored in the index 3 position of the image array, that is, <yourArrayName>[3].src.  Thus the whiteout() event handler function is a loop from 0 to 48 assigning the document.images elements the white box, analogous to the check in part B4.  (Notice that you can also use a loop within a loop, each with seven iterations, as if visiting rows and columns; if i is the outer loop iteration variable and j is the inner loop iteration variable, the positions of document.images being updated are i*7+j.   

 

Test the Clear button clears a pattern of blue boxes in the pattern grid.

 

C7.  Allow for Resetting Clicks. If a person makes a mistake, clicking on the wrong square, it would be handy to be able to click on it again and clear it. To do this, we need to know whether the square has been clicked before.  By keeping a record of which squares were clicked, we can know whether to set it to blue (the first time) or white.  The process requires the following steps:

a)      Declare a variable setOrNo as an array with 49 items, because any of the pattern squares can be set.

b)      We will use 0 to indicate the square has not been set and 1 to indicate that it has been.  Initialize the array to zero in the loop that you wrote in step C2.  (This is a good logical place to initialize setOrNo because the squares are being set up to be white, and a 0 initialization will indicate that.

c)      Make one further change to the fire() event handler.  Rather than displaying blue every time, use an if statement to check to see if setOrNo[row*7+col] is equal to 0. If it is, set the square to blue, as usual. If not, it is already blue, so set it to white.

Test out your solution and be sure that two clicks on a square set back to white.

 

C8.  Turn In.  Publish your new page in your Web space under a unique name.  

a)      Have your Pattern Fill page published by 2:00 AM, Monday, Feb. 24.

b)      Do not modify your page until after it is graded.

c)      Send an email message to your TA giving the URL for your page.

d)      Print the HTML/JavaScript source, add your name, address and section number, and turn it in in class.

 

Project 2d Completion

 

The goal of Part 2D is to complete the Orange Concentrate Application.

 

D1.  Create a new page. Make a copy of your working version of Project 2C. (A copy is available here.)  Change the heading to reflect the new task of Orange Concentrate. Also, include the randNum() function given in the book, p. 377.

 

D2. Create Control Buttons.  Add buttons to the form created in the C5.  These buttons and their click event handlers should be

a)      “Clear” calls whiteout().

b)      “View” calls show().

c)      “Check” calls check().

d)      “New” calls setUp().

 

D2.  Create a Random Pattern.  Declare variables squares, initialized to 3, and two ten-element arrays, probr and probc. These two arrays will hold the random positions of the pattern, probr containing its row position, and probc containing its column position.  The variable squares is the number of elements squares in the pattern.  So, initializing the random positions will be a function, setUp() with three steps:

a)      Clear the array by making a call on whiteout().

b)      Set up a loop iterating squares times, and on the ith iteration assign a random number over a range = 7 (0 through 6) to probr[i] and a random number over the same range to probc[i].

c)      Display the random pattern with a call to show(), which is a new function written in the next part.

Notice that one shortcoming of the application (which we will not worry about) is that two random positions could be identical, lowering the number of squares below the squares count.

 

 

D3.  Write the show() Function.  The show() function copies the random pattern into the pattern grid.  It simply requires a loop of squares iterations in which on the ith iteration the square with row position probr[i] and the column position probc[i] is set to red.  This is, by now, a standard operation.

 

Next declare a variable, timerID, and add to the end of the show() function a call to clear the pattern grid after five seconds. The timer call, as explained on p. 402, has the form

 

     timerID = setTimeout("whiteout()”, 5000);

 

which will clear the pattern grid after the indicated amount of time.

 

D4.  Write the check() Function.  To check how the user has done with the concentration test, we simply go through the pattern and see if the position is set by the user or not, as indicated in the setOrNo. If it is set, then the user got the position, and we should draw it purple. If the position is not set, it should be drawn in red to show it was part of the original pattern. The steps are

a)      Create a loop for squares iterations.

b)      On the ith iteration, use an if statement to see if probr[i]*7 + probc[i] is set.

c)      If the position is set (1), fill the position in purple, which has been prefetched in Part 2, and is (probably) stored in the image array at index position 5.

d)      If the position is not set (0), fill the position in red.

 

D5.  [Extra Credit]  Add Controls. First, change the number of squares in the pattern. Doing so requires adding or subtracting one from squares.  It is suggested that you use a function, of the form,

 

            squares = Math.min(10, squares+1)

 

which keeps squares from getting too large.  Math.min returns the smaller of its two arguments.  For subtracting, there is also a Math.max.  Also, control the time of the application.  This will require the use of the min and max functions, and will work in units of 1000, since time is measured in milliseconds.

 

D6. [Extra Credit]  Improve the Looks. Make the Orange Concentrate application nicer visually by embedding it in a table and arranging the controls conveniently. Try to make the application as nice as possible, perhaps even renaming it.

 

C7.  Turn In.  Publish your new page in your Web space under a unique name.  

a)      Have your completed page published by 2:00 AM, Thursday, Feb. 27.

b)      Do not modify your page until after it is graded.

c)      Send an email message to your TA giving the URL for your page.

d)      Print the HTML/JavaScript source, add your name, address and section number, and turn it in in class.