Computing index
EXAMPLE 1
WAGNER LYRIC QUIZ

[ Example 1 | Example 2 | Example 3 ]


Before reading on you may first want to
  • Use the script - if you have never used the script before.
  • View the script - to see the script in a fresh window to refer to as you read this guide.



What the script does

    The Wagner Lyric Quiz was the first JavaScript I ever wrote. The puzzle is for the user to guess the song title based on the lyrics written on the page in Ye Olde English. Its purpose, when written, was to pull visitors back to my site as I changed the puzzles (lyrics) periodically.

    The script is very simple:- all it needs to do is read in a guess from the user, check the text entered against the list of song titles and output a reply (based on how many guesses have been made) reporting if the guess is wrong or right.



User input

    First of all the user needs to choose a lyric to guess at. This is done with a select object called lyricno.


    We could give each option a value but the number of the lyric can easily be calculated from the index of the selected option.


    Next the user needs to enter a guess. A text object called guess is used and the onChange attribute set to trigger a comparison of the users guess and the answer whenever a guess is entered.



    A second text box called reply is placed below which will display any response made by the program to a users guess.


    Finally a button is included to allow the user to give in and see the answer.




Program variables

    The first variable is called ResponseText and is an array of 5 strings - defined as:

ResponseText = new Array ("   ...TRY AGAIN...", "   ...HAVE ANOTHER GO...",
                       "   ...NOPE !"      , "   ...WRONG !"           , "   ...GIVE IN ?")
    Whenever a user guesses incorrectly, the program will respond by displaying one of the messages in this array.

    We now need variables to store information on the 6 songs in the quiz. To do this we use arrays (of length 6) to store the details:

AnswerArray = new Array ("BOHEMIAN RHAPSODY", "LIVIN ON A PRAYER",
                         "THE BOXER"        , "BORN TO BE WILD"  ,
                         "WANABE"           , "ITS A SIN"          )

DisplayArray = new Array ("Bohemian Rhapsody  by Queen"    , "Livin\' On A Prayer  by Bon Jovi",
                          "The Boxer  by Simon & Garfunkel", "Born To Be Wild  by Steppenwolf" ,
                          "Wannabe  by Spice Girls"        , "It\'s A Sin  by Pet Shop Boys"     )

   ReplyText = new Array ("", "", "", "", "", "")

   GuessText = new Array ("", "", "", "", "", "")

    NoOfTrys = new Array (0 , 0 , 0 , 0 , 0 , 0 )

    The AnswerArray stores the song titles for each song - this is what a user's guess will be matched against.
    The DisplayArray holds text that will be shown if the user guesses correctly or gives in.

    ReplyText and GuessText store the text shown in the input text boxes on screen. This is so the messages do not remain on screen when the user selects a new lyric to guess at, but are stored away. Should the user re-select the lyric, the messages for that lyric can be retrieved from these arrays and shown on screen.
    Similarly, the number of attempts at guessing each lyric are stored in the NoOfTrys array. So the program keeps track of how many guesses have been made at each and every lyric.

    The final variable in the script is CurLyric which is used to store the number of the lyric that is currently selected. It is initially set to zero:

    CurLyric = 0



How the script operates


1.   The user selects a lyric

    To begin with the user must select a lyric to make a guess at. When the lyricno option is changed the input tag will automatically call the NextLyric function.

    The function is called with parameter formName. This is simply used as a shortcut to save having to type document.Quiz.
i.e. 'formName' = 'document.Quiz'
So the value of the guess text object: document.Quiz.guess.value
can now be written as: formName.guess.value

    The first job for the NextLyric function is to store the current display of the two text boxes on the screen into the appropriate arrays:

ReplyText[CurLyric] = formName.reply.value
GuessText[CurLyric] = formName.guess.value

    Next the script looks at the lyricno select object. The number of the lyric selected will be the index of the selected option in the menu.
CurLyric = formName.lyricno.selectedIndex

    Once we know the number of the lyric the user has selected we can refresh the messages displayed on screen with the values stored in the ReplyText and GuessText arrays.
formName.reply.value = ReplyText[CurLyric]
formName.guess.value = GuessText[CurLyric]



2.   The user enters a guess

    Now the user will enter a guess for the lyric chosen. On pressing the return key, the onChange attribute of guess will call the Reply function with formName = document.Quiz

    The Reply function first checks that the guess is not blank:

if ( formName.guess.value!="" )

    ignoring the guess if it is empty. If, however, there is text entered into the guess box, then we check if the guess entered matches the correct answer
if ( CorrectAns(formName.guess.value) )
    we will return to see how the CorrectAns function works in a moment.

    If the answer is correct, then we call the function DisplayAns and display a message in the guess box to show the user guessed the answer correctly.

DisplayAns(formName)
formName.guess.value="   CORRECT !!"
    The DisplayAns function simply inserts the song title and artist, as stored in the DisplayArray, into the reply text box. It also calls the focus() method which moves the cursor from the reply text box to the guess text box.
formName.reply.value = DisplayArray[CurLyric]
formName.guess.focus()
    These statements are defined in a separate function so that when a user presses the give in button, the button can call the DisplayAns function to show the answer.

    Next we need to handle the case of a wrong guess. The Reply function calls another function Wrong to handle this:

Wrong(formName)

    The reply shown on screen will depend on how many attempts have so far been made to guess the lyric selected. These numbers are stored in the NoOfTrys array - so the number of guesses made at the current lyric is NoOfTrys[CurLyric].
    The messages to be shown are kept in the ResponseText array. Hence the message we want to show is ResponseText[NoOfTrys[CurLyric]], and is placed in the reply text box with the command:
formName.reply.value = ResponseText[NoOfTrys[CurLyric]]

    Now we have to increase the number of guesses made at this lyric. This is done using the ++ notation. However, we only have 5 reply strings, so when the number of trys reaches 5 we must reset the value to 4 (remember the array is indexed as 0 1 2 3 4).
NoOfTrys[CurLyric]++
if ( NoOfTrys[CurLyric]==5 )
      NoOfTrys[CurLyric]=4

    Finally, as with the DisplayAns function, we move the cursor into the guess text box using the focus() method.
formName.guess.focus()


    Now I return to the CorrectAns function. There is no real need for this function, we could check the answer by simply comparing strings with the condition:
if ( formName.guess.value==AnswerArray[CurLyric] )
    remembering the song titles are stored in the AnswerArray.

    However, this would assume the user entered the title in identical form as that in the array. The program needs to be aware that Livin' is equivalent to Living, etc.

    Although the nature of the procedure is more a matter of general programming rather than how to use JavaScript in a HTML file, it does include two JavaScript methods I have not covered and will pick out now.


    Firstly the toUpperCase method. The guess entered into the text box is converted into block capitals by the command:

GuessMade = GuessMade.toUpperCase()
    This ensures the comparison is not case sensitive.


    The general technique of the procedure is to move through the guess string (got) and check that characters match those in the want string. Because we are allowing for the odd typing error we use two pointers (gotCur and wantCur) to run through each string at a different rate. So we can check that the 4th character in got is the same as the 6th character in want.
    In order to test characters in the strings, we use the substring method.
    Thus, the fourth character in the got string is:

got.substring(3,4)
    and the character at wantCur in the want string is found by:
want.substring(wantCur,wantCur+1)



3.   The user enters a guess into the reply box

    The processing of a guess can only handle text entered into the guess text box. So if a user mistakenly enters a guess into the reply box, we can save the user having to enter their guess again by copying the text across.

    So when the value in the reply is changed, the OtherBox function is called.
    First we output a message in an alert window to tell the user they have typed their guess into the wrong box:

alert('Type your guess into the \n upper \'Guess\' text box')

    Now we copy the text from the reply box into the guess box and set the reply box to be empty.
formName.guess.value = formName.reply.value
formName.reply.value = ""

    Finally we focus the cursor on the guess box, ready for the user to press return and enter the guess.
formName.guess.focus()



4.   The user gives in

    Because we placed the answer display procedure in a function of its own, and not inside the Reply function, the commands that handle a user giving in are already defined in the DisplayAns function.
    Hence,


    handles the showing of an answer correctly.



[ Index Page | HTML Guide | JavaScript | Free Images | My Scripts | Resources Links ]

©1998 Stephen Battey
This page hosted by Get your own free home page