Hello, this is my first post here, but I'm having some trouble figuring out what I messed up on my code :(

I'm making a Javascript game of Hangman for one of my classes and I originally had the input as a text box where you physically type in the letter and if it was wrong, it would draw the next sequence of the hangman picture and place the letter in another text box as a "Used Letters," or if you're right, it would place the letter you chose in the box for the word you're guessing. However, I decided that instead of doing that, I wanted to make it more visually appealing and add buttons with the letters on them instead as you can see here: www.mediafire.com/?mijjldzmmjd (the one with the _2 is the one I'm currently using, but the original is supplied as well).

The buttons register the correct letters just fine (you are able to win), but it still doesn't place the used letters in the right boxes (it is replacing them in the letters instead? - If you continue to click the same letter over and over, it will keep replacing the buttons with the same letter until they're all replaced and then it finally starts putting them in the "Used Letters" section, and finally the "word" section).

Any ideas? I'm sure there's some simple thing I'm missing, but I can't for the life of me find it. I'm only used to more simple coding, so troubleshooting on this large of a code is confusing me! haha

Recommended Answers

All 5 Replies

[link] .... What game of hangman? All I get is advertising with more advertising in a popup!!!! No game.

Airshow

[link] .... What game of hangman? All I get is advertising with more advertising in a popup!!!! No game.

Airshow

Odd, it goes directly to the download for me...

Here's the code I'm working with though, I figured downloading it would make it easier to see what I'm talking about as all the images are included:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Derek's Hangman Game - GIT215</title>

<script src="words.js">
</script>

<script>

wordNo = Math.round(Math.random() * (Array1.length-1))
imageNo = 2
word = new String(Array1[wordNo])

tries = 0

usedLetters = new Array()
letterPosition = word.length + 2

guess = ""

function checkGuess(letter) {
	startPoint = eval(-1)
	position = 0
	found = false
	
	document.forms[0].elements[letterPosition].value = letter
	letterPosition++
	

	while (position != -1) {
		position = word.indexOf (letter, startPoint + 1)
		if (position!=-1) {
			found = true;
			document.forms[0].elements[position].value = letter;
			startPoint = position;
		}
	}

		tries++
		if (!found) {
			document.images[0].src = "Images/hangman" + imageNo + ".png"
			imageNo++
			if (imageNo >= 12)
				lose()
			}

		guess = ""
		for (i=0; i< word.length; i++) {
			guess = guess + document.forms[0].elements[i].value
			}
		if(guess.length == word.length) {
			win()
		}
}

function lose() {
	alert ("You're Dead! The word was " + word)
	window.document.location = "hangman_2.html"
	}
	

function win() {
	
	word = word.toUpperCase()
	guess = guess.toUpperCase()

if (word == guess) {
		alert("Good Job!  You've saved your life... this time.")
		window.document.location = "hangman_2.html"
		}
	}



</script>

<style type="text/css">
	body {background-color: #1087d9;}
	body {color: #000}
</style>

</head>

<body>
<hr />
<hr />
<hr />
<hr />

<form>
	<table align="left" background="Images/background.png" width="600" height="600" border="0" cellspacing="30" cellpadding="0">
  		<tr>
    		<td align="center" rowspan="2" height="350" width="255">
    			<img src="Images/hangman1.png" />
    		</td>
            <td height="160" width="255" align="center">
				<input type="button" value="A" onClick="checkGuess(this.value)">
				<input type="button" value="B" onClick="checkGuess(this.value)">
				<input type="button" value="C" onClick="checkGuess(this.value)">
				<input type="button" value="D" onClick="checkGuess(this.value)">
				<input type="button" value="E" onClick="checkGuess(this.value)">
				<input type="button" value="F" onClick="checkGuess(this.value)">
				<input type="button" value="G" onClick="checkGuess(this.value)">
				<input type="button" value="H" onClick="checkGuess(this.value)">
				<input type="button" value="I" onClick="checkGuess(this.value)">
				<input type="button" value="J" onClick="checkGuess(this.value)">
				<input type="button" value="K" onClick="checkGuess(this.value)">
				<input type="button" value="L" onClick="checkGuess(this.value)">
				<input type="button" value="M" onClick="checkGuess(this.value)">
				<input type="button" value="N" onClick="checkGuess(this.value)">
				<input type="button" value="O" onClick="checkGuess(this.value)">
				<input type="button" value="P" onClick="checkGuess(this.value)">
				<input type="button" value="Q" onClick="checkGuess(this.value)">
				<input type="button" value="R" onClick="checkGuess(this.value)">
				<input type="button" value="S" onClick="checkGuess(this.value)">
				<input type="button" value="T" onClick="checkGuess(this.value)">
				<input type="button" value="U" onClick="checkGuess(this.value)">
				<input type="button" value="V" onClick="checkGuess(this.value)">
				<input type="button" value="W" onClick="checkGuess(this.value)">
				<input type="button" value="X" onClick="checkGuess(this.value)">
				<input type="button" value="Y" onClick="checkGuess(this.value)">
				<input type="button" value="Z" onClick="checkGuess(this.value)">
    		</td>
  		</tr>
        <tr>
        	<td height="160" width="255" align="center">
            	<h3>Letters Guessed:</h3>
				<p>
					<script>
							for (i=0; i<28; i++) {
								document.write("<input type=text size=1>")
							}
					</script>
				</p>
            </td>
        </tr>
        <tr>
    		<td colspan="2" height="160" width="540" align="center">
    			<script>
					for (i=0; i<word.length; i++) {
					document.write("<input type=text size=5 maxlength=1 value=''>")
					}
				</script>
    		</td>
  		</tr>
	</table>
</form>

<table align="center" width="600" border="0" cellspacing="30" cellpadding="0">
  <tr>
    <td>
    	<p><b>Hello and welcome to Derek's Javascript Hangman!</b></p>
        <p>This app was designed using tutorials and examples from various websites which are listed in the javascript code section.
        It was created soley in Adobe Dreamweaver, using Adobe Photoshop for the graphics.  Now let's get onto it, here's how to play:</p>
    </td>
  <tr>
  	<td>
        <h3 align="center">Instructions:</h3>
        <p>In the bottom window is displayed the number of letters in your word and your progress.</p>
        <p>Using the letters shown in the top right box, click the one one which you'd like to guess.</p>
        <p>As you click a letter, it will be added to the "Letters Guessed" window.</p>
        <p>You will not be penalized for selecting the same letter twice.        </p>
      <p>You have ten (10) tries before you are "hung."</p>
        <ul>
        	<li>The category is musical instruments, only one word will be used.</li>
        </ul>
    <p>Good Luck!</p></td>
  </tr>
</table>

<hr />
<hr />
<hr />
<hr />

</body>
</html>

Here's the original (working) code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Derek's Hangman Game - GIT215</title>

<script src="words.js">
</script>

<script>
wordNo = Math.round(Math.random() * (Array1.length-1))
imageNo = 2
word = new String(Array1[wordNo])

tries = 0

usedLetters = new Array()
usedLetterPosition = word.length + 2

guess = ""

function checkGuess() {
	startPoint = eval(-1)
	position = 0
	found = false
	letter=document.forms[0].elements['letterGuess'].value
	
	document.forms[0].elements[usedLetterPosition].value = letter
	usedLetterPosition++
	
	
	while (position != -1) {
		position = word.indexOf (letter, startPoint + 1)
		if (position!=-1) {
			found = true;
			document.forms[0].elements[position].value = letter;
			startPoint = position;
		}
	}
		tries++
		if (!found) {
			document.images[0].src = "Images/hangman" + imageNo + ".png"
			imageNo++
			if (imageNo >= 12)
				deadMan()
			}
		guess = ""
		for (i=0; i< word.length; i++) {
			guess = guess + document.forms[0].elements[i].value
			}
		if(guess.length == word.length) {
			guessWord()
		}
		document.forms[0].letterGuess.focus()
		document.forms[0].letterGuess.select()
}
	
function deadMan() {
	alert ("You're Dead! The word was " + word)
	window.document.location = "hangman.html"
	}
	
function guessWord() {
	
	word = word.toUpperCase()
	guess = guess.toUpperCase()
	
	if (word == guess) {
		alert("Good Job!  You've saved your life... this time.")
		window.document.location = "hangman.html"
		}
	}
	
</script>

<style type="text/css">
	body {background-color: #1087d9;}
	body {color: #000}
</style>

</head>

<body>

<p>
	<h2 align="center"><u>Hangman 2.13-1</u></h2>
</p>

<table align="left" width="600" height="400" border="0" cellspacing="30" cellpadding="0">
  <tr>
    <td>
    	<p><i>Hello and welcome to Derek Dinsmore's Javascript Hangman!</i></p>
        <p>This app was designed using tutorials and examples from various websites which are listed in the javascript code section.
        It was created soley in Adobe Dreamweaver, using Adobe Photoshop for the graphics.  Now let's get onto it, here's how to play:</p>
    </td>
  <tr>
  	<td>
        <h3 align="center">Instructions:</h3>
        <p>In the top hand corner is displayed the number of letters in your word.</p>
        <p>Using the input box underneath, type the letter of which you wish to guess.</p>
        <p>The box at the bottom will show the letters you've already picked.</p>
        <p>You have ten (10) tries before you are "hung," which will be displayed in the main window.</p>
        <ul>
        	<li>The category is musical instruments, only one word will be used.</li>
        </ul>
    </td>
  </tr>
</table>

<form>
	<table align="right" background="Images/background.png" width="600" height="600" border="0" cellspacing="30" cellpadding="0">
  		<tr>
    		<td rowspan="2" align="center" height="350" width="255">
    			<img src="Images/hangman1.png" />
    		</td>
    		<td height="160" width="255" align="center">
    			<script>
					for (i=0; i<word.length; i++) {
					document.write("<input type=text size=1 maxlength=1 value=''>")
					}
				</script>
    		</td>
  		</tr>
  		<tr>
    		<td height="160" width="255" align="center">
    			<p>
        			Guess a Letter:
        		</p>
        		<p>
					<input type="text" size="3" name="letterGuess">
        		</p>
        		<p>
					<input type="button" value="Submit" onClick="checkGuess()">
        		</p>
    		</td>
  		</tr>
  		<tr>
    		<td colspan="2"  height="160" width="540" align="center">
   				<p>
    				<h3>Letters You've Used:</h3>
    			</p>
				<p>
					<script>
						for (i=0; i<22; i++) {
							document.write("<input type=text size=1>")
						}
					</script>
     			</p>
    		</td>
  		</tr>
	</table>
</form>

</body>
</html>

Here's a link to the original code and the new code that I'm trying to get to work:

http://www.public.asu.edu/~ddinsmor/hangman.html
http://www.public.asu.edu/~ddinsmor/hangman_2.html

M.C.,

OK those new links work.

I have an idea. Instead of keeping a separate tally of letters used, why not disable the appropriate ABC... buttons as they are clicked (and change their appearance) instead. This will be easier to program and much more user friendly - double bonus.

Airshow

M.C.,

OK those new links work.

I have an idea. Instead of keeping a separate tally of letters used, why not disable the appropriate ABC... buttons as they are clicked (and change their appearance) instead. This will be easier to program and much more user friendly - double bonus.

Airshow

That was something I was considering, but I have no idea how to do it. I'm still learning JavaScript, so my knowledge is very limited.

I did realize though that the reason the buttons are duplicating the number is because I don't have names for the forms. Here's what I changed in the body:

<script>
		for (i=0; i<28; i++) {
		document.write("<input type=text [B]name=usedLetters[/B] size=1>")
							}
</script>

and

<script>
		for (i=0; i<word.length; i++) {
		document.write("<input type=text [B]name=word[/B] size=5 maxlength=1  value=''>")
					}
</script>

But where exactly am I now placing the document.getElementsByName() in my code??

MC,

Here's a version to show how to disable buttons, which is made a lot easier by creating the buttons and word/letter elements in javascript rather than in HTML.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Derek's Hangman Game - GIT215</title>
<style type="text/css">
body {
	background-color: #1087d9;
	color: #000;
}
#word {
	margin: 0;
	padding: 10px;
	list-style-type: none;
	border: 1px solid #000;
}
#word li {
	display: inline;
	width: 25px;
	margin: 0 3px;
	padding: 3px 9px;
	border: 2px solid #000;
	background-color: #FFF;
	font-family: monospace, courier;
	font-size: 12pt;
}
input.alpahabetButton {
	margin: 3px;
	padding: 3px 6px;
	font-family: monospace, courier;
	font-size: 12pt;
	color: #000;
}
input.disabled {
	margin: 3px;
	padding: 3px 6px;
	font-family: monospace, courier;
	font-size: 12pt;
	color: #999;
}
</style>

<script src="words.js"></script>

<script>
onload = function(){
	var Array1 = ['London', 'Paris', 'Chicago'];
	var wordNo = Math.round(Math.random() * (Array1.length-1));
	var word = Array1[wordNo].toUpperCase();
	var aWord = [];//Lookup array to avoid need for document.getElementById in scanWord().
	var imageNo = 2;
	var lettersFound = 0;
	var i;
	var wordContainer = document.getElementById('word');
	var alphabetContainer = document.getElementById('alphabetContainer');
	var el;
	var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	for (i=0; i<26; i++) {//Loop to create ABC... buttons
		el = document.createElement('input');
		el.className = 'alpahabetButton';
		el.type = 'button';
		el.value = alphabet.charAt(i);
		el.onclick = checkGuess;//Attach onclick handler to button
		alphabetContainer.appendChild(el);
	}
	for (i=0; i<word.length; i++) {//Loop to create empty word elements
		el = document.createElement('li');
		el.innerHTML = '&nbsp;'
		wordContainer.appendChild(el);
		aWord.push(el);
	}
	function checkGuess(){//This "supervisor" function is called when an alpahabet button is clicked
		this.onclick = function(){};//Disable button
		this.className = 'disabled';//Indicate disabled
		if(!scanWord(this.value)) {//If letter not found in word ...
			if(hangSomeMore() >= 12) { lose(); }//... then update graphic and test to see if threshold reached.
		}
		else {//If letter was found in word ...
			if (lettersFound === word.length) { win(); }//... test to see if word completed
		}
	}
	function scanWord(letter){
		var i, found=false;
		for (i=0; i<word.length; i++) {
			if(word.charAt(i) === letter){
				aWord[i].innerHTML = letter;
				found = true;
				lettersFound++;
			}
		}
		return found;
	}
	function hangSomeMore(){
		document.images[0].src = "Images/hangman" + imageNo++ + ".png";
		return imageNo;
	}
	function lose() {
		if(confirm("You're Dead! The word was " + word + ".\n\nPlay again?")){
			window.document.location = "hangman.html";
		}
	}
	function win() {
		if(confirm("Good Job!  You've saved your life... this time.\n\nPlay again?")){
			window.document.location = "hangman.html";
		}
	}
}
</script>
</head>

<body>

<form>
<table align="left" background="Images/background.png" width="600" height="600" border="0" cellspacing="30" cellpadding="0">
<tr>
<td align="center" rowspan="2" height="350" width="255">
<img src="Images/hangman1.png" />
</td>
<td id="alphabetContainer" height="160" width="255" align="center"></td>
</tr>
<tr>
<td colspan="2" height="160" width="540" align="center">
<ul id="word"></ul>
</td>
</tr>
</table>
</form>

<table align="center" width="600" border="0" cellspacing="30" cellpadding="0">
<tr>
<td>
<p><b>Hello and welcome to Derek's Javascript Hangman!</b></p>
<p>This app was designed using tutorials and examples from various websites which are listed in the javascript code section.
It was created soley in Adobe Dreamweaver, using Adobe Photoshop for the graphics.  Now let's get onto it, here's how to play:</p>
</td>
<tr>
<td>
<h3 align="center">Instructions:</h3>
<p>In the bottom window is displayed the number of letters in your word and your progress.</p>
<p>Using the letters shown in the top right box, click the one one which you'd like to guess.</p>
<p>As you click a letter, it will be disabled to prevent you selecting it again.</p>
<p>You have ten (10) unsuccessful tries before you are "hung."</p>
<ul>
<li>The category is musical instruments, only one word will be used.</li>
</ul>
<p>Good Luck!</p></td>
</tr>
</table>

</body>
</html>

As you see the whole thing is wrapped in an anonymous onload function. This will seem a bit odd if you've not seen this pattern before but actually makes life a lot simpler once you've got used to it.

You will also see that I have split out some of the checking code into two separate "worker" functions ( scanWord and hangSomeMore ), thus making the main checking function into a much simpler "supervisor". Returned values from scanWord and hangSomeMore are key to the way the supervisor tests to see whether it should call win or lose (or neither).

Airshow

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.