1. Home
  2. Computing & Technology
  3. JavaScript

Hangman Script Tutorial

page five

clr gif

 

<< Previous Page

function selectLetter(s) {
s = parseInt(s);
var ch = String.fromCharCode(s+65);
if (answer.indexOf(ch) == -1) w++;
al = al.substring(0,s) + ch + al.substring(s+1,al.length);
var opty = Math.floor(Math.random()*165)*71 + opt;
top.location = page + '?opt='+opty+'&al='+al+'&w='+wr.charAt(wx);
return false;
}

The selectLetter function is passed a number between 0 and 25 representing a letter of the alphabet. By adding 65 to this number we get the ASCII code for the letter and the fromCharCode global method gives us the letter itself. We then test if this letter is in the answer string by using the indexOf method. If it isn't in the string we add one to the wrong answer count. We then substitute the letter for the appropriate dash in the selected guess string (the number passed gives the position). The option number representing the position of the correct answer in the array is then encoded. To do this we start by generating a random number between 0 and 164 and then multiplying it by 71. This effectively gives us a number between 0 and 11644 that we know is divisible by 71. We then add the position of the correct answer to this number which means that the modulus 71 of the number will be the position of the correct answer. The page is then reloaded passing the updated values. The return statement should never be reached.

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.