PDA

View Full Version : Javascript Game Help



IvyF
07-01-2010, 05:17 PM
I am creating a guessing word game (That only has one answer) that when the user types in a guess the innerHTML will display the number of letters user got right from the answer. The user only has five tries before game over.

My problem is my innerHTML is still displaying 0 matches, even when put the answer in. Is there something can I do differently?

Here is the 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>Midterm game</title>
<script language="javascript">
var word = "album";
var tries = 0;
var count = 0;
function guessing()
{
tries++;
guess = document.getElementById("txt1").value = "";

for(i = 0; i<guess.length; i++)
{

if(guess[i] === word)
{
alert("Congradulations! You got it!");
count++;
break;
}
}

document.getElementById("result").innerHTML = "You have " + count + " matches";
if(tries > 5)
{
alert("Sorry, game over!");
}

}
</script>
</head>

<body>
<h1>Jotto</h1>
<b><p>Guess the five letter word! You get 5 tries.</p></b>
<form>
<p><input type="text" id="txt1" /></p>
<p><input type="button" id="btn1" value="Guess" onclick="guessing()" /></p>
<p><div id="result"></div></p>
</form>
</body>
</html>

vwphillips
07-02-2010, 09:46 AM
<!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>Midterm game</title>
<script type="text/javascript">
var word = "album";
var tries = 0;

function guessing(){
tries++;
var guess = document.getElementById("txt1").value;
if(guess === word){
alert("Congradulations! You got it!");
}
var count = 0;
for (var z0=0;z0<word.length;z0++){
if (word.charAt(z0)==guess.charAt(z0)){
count++;
}
}
document.getElementById("result").innerHTML = "You have " + (count) + " matches";
if(tries > 5){
alert("Sorry, game over!");
}
}

</script>
</head>

<body>
<h1>Jotto</h1>
<b><p>Guess the five letter word! You get 5 tries.</p></b>
<form>
<p><input type="text" id="txt1" /></p>
<p><input type="button" id="btn1" value="Guess" onclick="guessing()" /></p>
<p><div id="result"></div></p>
</form>
</body>
</html>