Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Forms in JavaScript Game

Status
Not open for further replies.

MatrixClaw

Programmer
Dec 7, 2009
7
US
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 in the code which is down-loadable in the attachment (the one with the _2 is the one I'm currently using, but the original is supplied as well), the buttons register for the picture changing, but do not register for the "Used Letters" field or for filling in the actual word. One of the button's values is also replaced by "undefined" after each click of another button and I'm not really sure why :confused:

If anyone could take a look at my code and see if you can figure out what the deal is, that'd be awesome!
 
I'm getting a bunch of undefined variable errors. You should really take care of those errors before trying to work out why something else doesn't work.

However, if I where you, I'd simply pass the letter being clicked to the function. Instead of having to sort through 26 inputs to find the one that was pressed.

Code:
<input type="button" value="A" id="letterGuess" onClick="checkGuess([red]this[/red])">
...
Code:
function checkGuess([red]letterguess[/red]) {
	...
letter=[red]letterguess[/red].value;
...

With that you now have the letter that was pressed without doing a bunch of getElementbyId and sorting through the inputs etc...


----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
Interesting, I hadn't even thought of that!

It seems to work now, though it still doesn't register anything in the text boxes I've made. Instead of saying "Undefined" now, it just duplicates whatever button I press by replacing another one with that letter. I'm sure it's something easy I'm not seeing, but I can't figure out where I went wrong here!
 
We'd need to see the updated code with the changes you've
made.

Just post it directly here between code tags:
[ignore]
Code:
code goes here
[/ignore]

Anyway, I would do away with all the textboxes, and just disable the buttons once they are clicked. When the game is over you can reset them.

So in the function that gets the letter disable the button at the same time.
Code:
letterguess.disabled=true;


----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
Here's what I have so far:

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

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

<script>
	//Randomly chooses the word from the array in words.js
wordNo = Math.round(Math.random() * (Array1.length-1))
imageNo = 2
word = new String(Array1[wordNo])
	//Sets tries to 0
tries = 0
	//Defines the used letters section and where it will place them
usedLetters = new Array()
letterPosition = word.length + 2

guess = ""
	//Checks your guess against the word
function checkGuess(letter) {
	startPoint = eval(-1)
	position = 0
	found = false
	
	document.forms[0].elements[letterPosition].value = letter
	letterPosition++
	
		//If letter is guessed right, this defines where to place the letter
	while (position != -1) {
		position = word.indexOf (letter, startPoint + 1)
		if (position!=-1) {
			found = true;
			document.forms[0].elements[position].value = letter;
			startPoint = position;
		}
	}
			//If guess is wrong, this places the next image in the sequence on the screen and takes off 1 try, calls for lose sequence if tries are all used
		tries++
		if (!found) {
			document.images[0].src = "Images/hangman" + imageNo + ".png"
			imageNo++
			if (imageNo >= 12)
				lose()
			}
			//If guess is right, this defines it at right and also calls for win sequence if all letters are guessed correctly
		guess = ""
		for (i=0; i< word.length; i++) {
			guess = guess + document.forms[0].elements[i].value
			}
		if(guess.length == word.length) {
			win()
		}
}
	//Defines what happens if you lose - Alert shows you lose and the word, reloads page to original state
function lose() {
	alert ("You're Dead! The word was " + word)
	window.document.location = "hangman_2.html"
	}
	
	//Defines what happens if you win - Alert says you win, reloads page to original state
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" name="letterGuess" onClick="checkGuess(this.value)">
				<input type="button" value="B" name="letterGuess" onClick="checkGuess(this.value)">
				<input type="button" value="C" name="letterGuess" onClick="checkGuess(this.value)">
				<input type="button" value="D" name="letterGuess" onClick="checkGuess(this.value)">
				<input type="button" value="E" name="letterGuess" onClick="checkGuess(this.value)">
				<input type="button" value="F" name="letterGuess" onClick="checkGuess(this.value)">
				<input type="button" value="G" name="letterGuess" onClick="checkGuess(this.value)">
				<input type="button" value="H" name="letterGuess" onClick="checkGuess(this.value)">
				<input type="button" value="I" name="letterGuess" onClick="checkGuess(this.value)">
				<input type="button" value="J" name="letterGuess" onClick="checkGuess(this.value)">
				<input type="button" value="K" name="letterGuess" onClick="checkGuess(this.value)">
				<input type="button" value="L" name="letterGuess" onClick="checkGuess(this.value)">
				<input type="button" value="M" name="letterGuess" onClick="checkGuess(this.value)">
				<input type="button" value="N" name="letterGuess" onClick="checkGuess(this.value)">
				<input type="button" value="O" name="letterGuess" onClick="checkGuess(this.value)">
				<input type="button" value="P" name="letterGuess" onClick="checkGuess(this.value)">
				<input type="button" value="Q" name="letterGuess" onClick="checkGuess(this.value)">
				<input type="button" value="R" name="letterGuess" onClick="checkGuess(this.value)">
				<input type="button" value="S" name="letterGuess" onClick="checkGuess(this.value)">
				<input type="button" value="T" name="letterGuess" onClick="checkGuess(this.value)">
				<input type="button" value="U" name="letterGuess" onClick="checkGuess(this.value)">
				<input type="button" value="V" name="letterGuess" onClick="checkGuess(this.value)">
				<input type="button" value="W" name="letterGuess" onClick="checkGuess(this.value)">
				<input type="button" value="X" name="letterGuess" onClick="checkGuess(this.value)">
				<input type="button" value="Y" name="letterGuess" onClick="checkGuess(this.value)">
				<input type="button" value="Z" name="letterGuess" 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>
 
This line:

document.forms[0].elements[letterPosition].value = letter;


Is setting the value of one of the items in the elements array of the form to the value stored inside the letter variable.

However the elements array includes not only your programmatically generated inputs, but also the letter buttons as well as the textboxes for the word to be guessed. Which is why your buttons are getting the values of the chosen letters.

I would give the inputs a name such as name="usedletters" and use that to place the used letters in the text boxes.

I would also give the textboxes for the word a name to identify them.






----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
So I'd be changing the script inside the body to:

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

and

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

Correct?

I figured that was the problem, but I wasn't sure where I define in the script itself these variables then. What would I need to change?

Thanks for all the help so far, I'm still trying to make sense of JavaScript so my knowledge on the subject is somewhat limited ;)
 
That's correct.
Then, simply use a document.getElementsBy[red]Name[/red] function to get the array of 'usedletter' textboxes.

Then you can check whether there's already a value and if there is move on to the next one until you find an empty to one to put in the letter that has been just used.






----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
So then am I replacing the document.forms with document.getElementsByName("usedLetters") (the parts in bold)? I tried that, it didn't seem to work, so I'm guessing that's not right...?

I totally understood my code when using a text input, but after I decided to put buttons instead, my confusion just went through the roof.

Code:
<script>

	//Randomly chooses the word from the array in words.js
wordNo = Math.round(Math.random() * (Array1.length-1))
imageNo = 2
word = new String(Array1[wordNo])
	//Sets tries to 0
tries = 0
	//Defines the used letters section and where it will place them
usedLetters = new Array()
letterPosition = word.length + 2

guess = ""
	//Checks your guess against the word
function checkGuess(letter) {
	startPoint = eval(-1)
	position = 0
	found = false
	
	[B]document.forms[0].elements[letterPosition].value = letter[/B]
	letterPosition++
	
		//If letter is guessed right, this defines where to place the letter
	while (position != -1) {
		position = word.indexOf (letter, startPoint + 1)
		if (position!=-1) {
			found = true;
			[B]document.forms[0].elements[position].value = letter;[/B]
			startPoint = position;
		}
	}
			//If guess is wrong, this places the next image in the sequence on the screen and takes off 1 try, calls for lose sequence if tries are all used
		tries++
		if (!found) {
			document.images[0].src = "Images/hangman" + imageNo + ".png"
			imageNo++
			if (imageNo >= 12)
				lose()
			}
			//If guess is right, this defines it at right and also calls for win sequence if all letters are guessed correctly
		guess = ""
		for (i=0; i< word.length; i++) {
			guess = guess + document.forms[0].elements[i].value
			}
		if(guess.length == word.length) {
			win()
		}
}
	//Defines what happens if you lose - Alert shows you lose and the word, reloads page to original state
function lose() {
	alert ("You're Dead! The word was " + word)
	window.document.location = "hangman_2.html"
	}
	
	//Defines what happens if you win - Alert says you win, reloads page to original state
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>
[/CODE
 
Here's a very small script on the basic usage of GetElementsByName

Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "[URL unfurl="true"]http://www.w3.org/TR/html4/loose.dtd"><html>[/URL]
<head>
<title>Example</title>
<script>

function Put_Value(Button_Obj){
var mytexts=document.getElementsByName('mytexts');

mytexts[1].value=Button_Obj;


}

</script>
</head>
<body>
<button name="mybuttons" value="A" onClick="Put_Value(this); return false;">A</button>
<button name="mybuttons" value="B" onClick="Put_Value(this); return false;">B</button>
<button name="mybuttons" value="C" onClick="Put_Value(this);" return false;>C</button>
<hr>
<input type=text name="mytexts" size=3><input type=text name="mytexts" size=3><input type=text name="mytexts" size=3>
</form>


</body>
</html>

Basically all this is doing is calling the function Put_Value every time a button is clicked and passing it the object reference the button. That's what the "this" parameter is for.

It then Uses GetElementsByName to get an array of the text boxes underneath. And then places the value obtained from the clicked button in one of those boxes. In the example it uses the middle text box but you can point it to any of the three by changing the number in mytexts[1].value to another one. Either 0, 1, or 2, a there are only 3 boxes.


----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top