1. Home
  2. Computing & Technology
  3. JavaScript

Hangman Script Tutorial

page two

clr gif

 

<< Previous Page

var qsParm = new Array();
function qs() {..}
qsParm['opt'] = null;
qsParm['al'] = null;
qsParm['w'] = null;
qs();

This code sets up an array to use for the query string passed to the page and initialises the entries in the array that we expect to retrieve. The qs function is not shown because it is exactly the same function as described in my query string tutorial.

var win = 0;
if (qsParm['win']) win = parseInt(qsParm['win']);
var opt = -1;
if (qsParm['opt']) opt = qsParm['opt']%71;
else opt = Math.floor(Math.random()*opts.length);

The win parameter is an optional one that will be passed at the end of the game to indicate if the game is won or lost. If it isn't there we are going to use a value of zero to indicate that the game is not yet completed.

The opt parameter should be there every time except when starting a new game. It reads in a number that indicates which answer in the answer array is the correct one. The modulus 71 converts the encoded number back into a straight array counter. If this parameter is not present then we are starting a new game and so we use Math.random to generate a random number between 0 and 1, multiply it by the number of entries in the opts array (using the length method) and then use the Math.floor function to round that down to the nearest integer giving us a random position within the opts array (which contains the encrypted versions of all of the answers).

Explore JavaScript
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.