Compare and Count Character help

1 replies
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? Any help would appreciated.

Here is the code:

Code:
<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(word)
{
 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!");
 }
 
}
function cc()
{
 var letter = guess.charAt(0)
}
</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>
#character #compare #count
  • Here you go:

    Code:
    <html>
    <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;
    var count = 0;
    var maxTries = 5;
    function guessing()
    {
    	if(tries < maxTries)
    	{
    		var guess = document.getElementById('txt1').value
    		count = 0;
    		tries++;
    
    		// Won the Game
    		if(guess == word)
    		{
    			alert("Congratulations! You got it!");
    			tries = maxTries;
    		}
    		// Still Guessing
    		else
    		{
    			// Count Matching Characters
    			for(i = 0; i < word.length; i++)
    			{
    				for(j = 0; j < guess.length; j++)
    				{
    					if(word.charAt(i) == guess.charAt(j)) {count++;}
    				}
    			}
    
    			// Display Matches
    			document.getElementById("result").innerHTML = "You have " + count + " matches";
    		}
    	}
    	// Too Many Tries
    	else
    	{
    		alert("Sorry, game over!");
    	} 
    }
    </script>
    
    </head>
    <body>
    <h1>Jotto</h1>
    <b><p>Guess the five letter word! You get 5 tries.</p></b>
    <form method="post" action="">
      <p><input type="text" id="txt1" value="" /></p>
     <p><input type="button" id="btn1" value="Guess" onclick="guessing();" /></p>
        <p><div id="result"></div></p>
    
    </form>
    
    
    </body>
    </html>
    {{ DiscussionBoard.errors[2290520].message }}

Trending Topics