Putting Together a Javascript Hangman Game

Learning how to manipulate stings is an important component of being able to build usable web applications. The develoepr must be able to take in some input, process it and return to the ser some form of meaningful output.

In this example you will get four files. This is what your game will look like when it’s finished:

hangman

Source Demo

So there you have it, a lovley hangman game to develop further and impress your friends with. The following is the code to the other files contained within the source folder.

First off let me show you hangman.htm

<!DOCTYPE html>
<html>
    <head>
        <title>Hangman</title>
        <link type="text/css" rel="stylesheet" media="screen" href="assets/css/style.css" />
        <script type="text/JavaScript" src="assets/js/script.js" ></script>
    </head>
    <body>
        <div id="container">
            <div id="head"><a name="_top">Get ready to play</a></div>
            <div id="body">
                <div id="body_head">Hangman</div>

                <div id="body_image">
                    <script>
                        if (window.innerWidth == null) {
                            intWidth = document.body.clientWidth;
                            intHeight = document.body.clientHeight;
                        }
                        else {
                            intWidth = window.innerWidth;
                            intHeight = window.innerHeight;
                        }
                        if (intWidth >= intHeight) {
                            intHeight = Math.round(intHeight * 0.4);
                            intWidth = Math.round(180 * intHeight / 240);
                        }
                        else {
                            intWidth = Math.round(intWidth * 0.4);
                            intHeight = Math.round(240 * intWidth / 180);
                        }
                        doc.write('<img name="PicHang" src="assets/images/Hangman_11.jpg" width="' + intWidth + '" height="' + intHeight + '" id="PicHang" alt="PicHang"/>');
                    </script>
                    <noscript>You do not appear to have JavaScript capabilities. This game is written in JavaScript.</noscript>

                </div>

                <div id="body_footer">Don't Get Dead!!</div>
            </div>
            <div id="response">
                <form name="Game" action="./hangman.htm" method="post">
                    <input type="text" name="TWord" id="TWord" />
                    <label for="TGuess">What's your guess?</label>
                    <input type="text" name="TGuess" id="TGuess" maxlength="1" />
                    <input type="text" name="TAnswer" id="TAnswer" />

                    <input type="button" class="action_buttons" name="check" id="check" onclick="CheckGuess();" value="Check" >
                    <input type="button" class="action_buttons" name="start" id="start" onclick="StartOver();" value="Start" >

                    <input type="text" name="TMessage" id="TMessage" />
                    <label for="TGuess">You have used the following letters:</label>
                    <input type="text" name="TPrevious" id="TPrevious" />
                </form>
            </div>
            <div id="guess">

            </div>
            <div id="footer">
                <script>document.write('<a href="#_top" onClick="javascript:ShowHelp()" >HELP</a>');</script>
                <noscript><hr />
                    You do not appear to have JavaScript capabilities. This game is written in JavaScript.
                </noscript>
            </div>
        </div>
    </body>
</html>

Next up, is the help file that we will be using javascript to open in a new window, help_popup.htm

<!DOCTYPE html>
<html>
    <head>
        <title>Hangman</title>
        <link type="text/css" rel="stylesheet" media="screen" href="assets/css/style.css" />
		<script type="text/JavaScript">
			function closeWindow(){
				window.close();
			}
		</script>
    </head>
    <body>
        <div id="container">
            <div id="head">help</div>
			<p>boy am i glad that hangman is over... still some things bothering me, i'll get back to them,</p>
            <p><a target="_parent" href="#head" onClick="javascript:closeWindow();" >close</a></p>
    </body>
</html>

This is the interesting file, script.js

window.onload = init();
var doc = document;
var p;
var preLoad;
var curWord;
var word;
var curPic = -1;
var count = 0;
var gcount = 0;

function init(){
    var Pic = new Array();	  //Declare the new array
    Pic[0] = 'assets/images/Hangman_1.jpg'; //Assign values to each element of
    Pic[1] = 'assets/images/Hangman_2.jpg'; //the array
    Pic[2] = 'assets/images/Hangman_3.jpg';
    Pic[3] = 'assets/images/Hangman_4.jpg';
    Pic[4] = 'assets/images/Hangman_5.jpg';
    Pic[5] = 'assets/images/Hangman_6.jpg';
    Pic[6] = 'assets/images/Hangman_7.jpg';
    Pic[7] = 'assets/images/Hangman_8.jpg';
    Pic[8] = 'assets/images/Hangman_9.jpg';
    Pic[9] = 'assets/images/Hangman_10.jpg';
    Pic[10] = 'assets/images/Hangman_11.jpg';

    p = Pic.length;
    preLoad = new Array();
    for(var i = 0; i < p; i++){
        preLoad[i] = new Image();
        preLoad[i].src = Pic[i];
    }

//add new words as you see fit the application will adapt to the new words.
    word = new Array();
    word[0] = 'JOKER';
    word[1] = 'TYPICAL';
    word[2] = 'GOOGLE';

    curWord = Math.floor(Math.random() * word.length)+1;
    StartOver;
}

function CheckGuess(){
    var curGuess = doc.Game.TGuess.value;

    if(count < 10){         if (curGuess != '' && curGuess != ' '){             var curPos = word[curWord].indexOf(curGuess.toUpperCase());             var nomPos = doc.Game.TWord.value.indexOf(curGuess);             if (curPos >= 0){

                //doc.Game.TMessage.value = doc.Game.TWord.value + ' ' + curGuess + ' ' + gcount + ' ';

                if(nomPos >= 0){

                    do{
                        gcount = gcount-1;
                        nomPos = doc.Game.TWord.value.indexOf(curGuess, (nomPos+1));
                    }while(nomPos > 0);
                //doc.Game.TMessage.value += ' ' + gcount + ' ' + doc.Game.TWord.value.indexOf(curGuess);
                }

                do{
                    gcount++;
                    doc.Game.TWord.value = DeBlankMachine(curWord, curPos, curGuess, doc.Game.TWord.value);
                    curPos = word[curWord].indexOf(curGuess.toUpperCase(), (curPos+1));
                } while(curPos > 0);
            }else{
                count++;
                if(doc.Game.TPrevious.value.indexOf(curGuess) >= 0){
                    count = count-1;
                }else{
                    doc.PicHang.src = preLoad[++curPic].src;
                    doc.Game.TPrevious.value += curGuess + ' ';
                }
            }
        }
    }else{
        doc.Game.TAnswer.value= word[curWord];
        doc.Game.TMessage.value = 'You Died, Press Start';
    }

    if(gcount == word[curWord].length){
        doc.Game.TAnswer.value= word[curWord];
        doc.Game.TMessage.value = 'You Win, Press Start';
        curPic = 11;
    }
    doc.Game.TGuess.value = '';

}

function StartOver(){
    curPic = 0;
    count = 0;
    gcount=0;
    doc.PicHang.src = preLoad[0].src;
    doc.Game.TGuess.value = '';
    doc.Game.TAnswer.value = '';
    doc.Game.TMessage.value = '';
    doc.Game.TPrevious.value = '';
    curWord = Math.floor(Math.random() * word.length);
    doc.Game.TWord.value = FillNewWord(curWord);
}

function FillNewWord(curWord, wpos, letter){
    var blankSpace = '';
    for(var j = 0; j < word[curWord].length; j++){
        blankSpace += "_ ";
    }
    return blankSpace;
}

function DeBlankMachine(curWord, wpos, letter, old){
    var oldArray = ExplodeStringToArray(old);

    for(var i = 0; i < word[curWord].length; i++){
        if(wpos == i){
            oldArray[2*i] = letter;
        }
    }

    return ImplodeArrayToString(oldArray)

}

function ExplodeStringToArray(string){
    var stringLength = string.length;
    var charArray = new Array(stringLength);

    for(var i = 0; i < stringLength; i++){
        charArray[i] = string.charAt(i);
    }

    return charArray;

}

function ImplodeArrayToString(array){
    var newString = '';

    for(var i = 0; i < array.length; i++){
        newString += array[i];
    }

    return newString;
}

function ShowHelp(){
    NewWindow = window.open('help_popup.htm','newWin','width=450,height=350, scrollbars=yes');
}

And finally weve got to style the thing, style.css

#container{width:180px; margin-left:auto;margin-right:auto; font-family:tahoma, arial, sans-serif; color:#333;}
#head {font-size:1.2em;}
#head, #body_head, #body_footer {font-weight:bold;}

#head, #body_head, #body_footer {text-align:center;}

#head{}

#body{}
#body_head{}
#body_image{}
#PicHang{border:1px solid #000;}
#body_footer{margin-bottom:5px;}

#response{}
#response{}

#response input#TWord, #response input#TGuess, #response input#TAnswer, #response input#TMessage,#response input#TPrevious {text-align:center; text-transform:uppercase; margin-top:5px; margin-bottom:5px;}
#response input#TWord, #response input#TAnswer, #response input#TMessage,#response input#TPrevious {border:0; border-bottom:1px solid #ccc; font-weight:bold; font-size:12px; color:#000080; width:180px;}
#response input#TGuess {width:15px;}
#response input#TAnswer {font-weight:bold; font-size:14px; color:#800000; width:180px;}
#response label{font-weight:bold;}
#response .action_buttons{width:80px; margin-left:5px; margin-top:5px; cursor:pointer;}
#guess{}
#footer{}

And thats it, a genuine, working hangman game, with proper string manipulation functions. Give it a go 🙂