1. Technology

Hangman Script Tutorial

page one

clr gif

The hangman script makes quite a lot of use of the various string methods. This makes it an interesting script to look at to see how these string methods can be combined together to produce a useful program. We're not just going to look at the string code though, we'll look at all of the code in this script and what the groups of statements are for so that you can see how I built this program and perhaps get some ideas of how you can build your own Javascript programs. The code for this script is rather long so I am not going to describe each statement individually, instead those individual statements of particular interest will be dealt with individually while the remainer of the code will be described in less detail. In any case working through this tutorial will give you an insight into how I develop Javascript programs.

We'll start at the beginning of the code and work our way through the code and consider what each individual statement (or group of statements) does and what purpose it serves in the program. In a lot of cases the most obvious code has not been used in this script and a more obscure method of achieving the same result has been substituted. This has been done deliberately in order to make it harder for someone to determine the correct answer by examining the source code.

The code for this game consists of two scripts, one that goes in the head of the page and one that goes in the body. The head script basically contains an array (opts) of encrypted possible answers. As that is all that the head script contains we'll move straight on to the body script. The body script performs the rest of the processing to select one of the answers in the opts array and runs the game.

var page = self.location.toString();
page = page.substr(0,page.indexOf('?'));

The code starts by retrieving the address of the current page. This allows you to name the page whatever you want and have multiple pages with hangman games on them without the games getting mixed up as to what belongs to which. The current page will be reloaded each time a guess is made.

©2014 About.com. All rights reserved.