4

I am making a little hang man game in HTML and I am trying to push a letter which the user has guessed correctly to where ever it needs to go in the div. Here is what I have so far:

var words = ['dog', 'mouse', 'horse', 'fossil', 'christmas', 'mountain', 'javascript', 'glitter', 'pringles', 'connect'];
var output = "";
var gRand = "";
var gWordAry = "";
function startGame() {
    var rand = words[Math.floor(Math.random() * words.length)]; //gets a random word from the array, stores as rand
    var wordAry = rand.split(''); //splits random word into its own array and each letter is in the array
    gRand = rand; //stores random word as global var
    gWordAry = wordAry;
    alert(wordAry);
    $('#hangmanGame').show();
    $('#startBtn').hide();
    //alert(rand);
    for (i = 0; i < wordAry.length; i++) { //draws a dash for every letter in the random word array after split
        //draw canvas dash
        output += ' _ ';
        $('#wordGuess').html(output);
    }


    //alert(output);


}

function guess(letter) {
    var letterID = letter.toLowerCase(); //converts letter to lowercase from html
    //alert(letterID);
    var foundLetter = 0;
    for (i=0;i<gWordAry.length; i++){
        if (gWordAry[i] == letterID){ //if a letter in the word array = the letter clicked this will run
            //alert('correct');
            foundLetter++;
            displayLetter(letterID);
        }
    }
    if (foundLetter == 0){ //if no letters in the array are found this will run
        alert('Try Again');
    }

}

function displayLetter(letterID){
    //displays all letters in the word
    $('#wordGuess').append(letterID)
}

HTML:

<div id="hangmanGame">
    <div id="wordGuess">  </div>  //THIS IS THE DIV WHERE THE LETTERS ARE GOING
    <table style="margin: auto;position: relative;top: 500px;">
        <tr> 
            <td><button class="alphabet" type="button"> </button></td>
            <td> <button type="button" onclick="guess('A')" id="1" class="alphabet">A </button></td> 
            <td> <button type="button" onclick="guess('B')" id="2" class="alphabet">B </button></td>
            <td> <button type="button" onclick="guess('C')" id="3" class="alphabet">C </button></td>
            <td> <button type="button" onclick="guess('D')" id="4" class="alphabet">D </button></td>
            <td> <button type="button" onclick="guess('E')" id="5" class="alphabet">E </button></td>
            <td> <button type="button" onclick="guess('F')" id="6" class="alphabet">F </button></td>
            <td> <button type="button" onclick="guess('G')" id="7" class="alphabet">G </button></td>
            <td> <button type="button" onclick="guess('H')" id="8" class="alphabet">H </button></td>
            <td> <button class="alphabet" type="button"> </button></td></tr>
        <tr> 
            <td> <button class="alphabet" type="button"> </button></td>
            <td> <button type="button" onclick="guess('I')" id="9" class="alphabet">I </button></td>
            <td> <button type="button" onclick="guess('J')" id="10" class="alphabet">J </button></td>
            <td> <button type="button" onclick="guess('K')" id="11" class="alphabet">K </button></td>
            <td> <button type="button" onclick="guess('L')" id="12" class="alphabet">L </button></td>
            <td> <button type="button" onclick="guess('M')" id="13" class="alphabet">M </button></td>
            <td> <button type="button" onclick="guess('N')" id="14" class="alphabet">N </button></td>
            <td> <button type="button" onclick="guess('O')" id="15" class="alphabet">O </button></td>
            <td> <button type="button" onclick="guess('P')" id="16" class="alphabet">P </button></td>
            <td><button class="alphabet" type="button"> </button></td></tr>
        <tr> <td> <button type="button" onclick="guess('Q')" id="17" class="alphabet">Q </button></td>
            <td> <button type="button" onclick="guess('R')" id="18" class="alphabet">R </button></td>
            <td> <button type="button" onclick="guess('S')" id="19" class="alphabet">S </button></td>
            <td> <button type="button" onclick="guess('T')" id="20" class="alphabet">T </button></td>
            <td> <button type="button" onclick="guess('U')" id="21" class="alphabet">U </button></td>
            <td> <button type="button" onclick="guess('V')" id="22" class="alphabet">V </button></td>
            <td> <button type="button" onclick="guess('W')" id="23" class="alphabet">W </button></td>
            <td> <button type="button" onclick="guess('X')" id="24" class="alphabet">X </button></td>
            <td> <button type="button" onclick="guess('Y')" id="25" class="alphabet">Y </button></td>
            <td> <button type="button" onclick="guess('Z')" id="26" class="alphabet">Z </button></td> </tr>
    </table>
</div>

The code may be a bit messy. I'm new to coding. Can anyone help? What I have at the moment adds the letter to the end of the _.

gkubed
  • 1,849
  • 3
  • 32
  • 45
kieron oates
  • 115
  • 1
  • 2
  • 15
  • when you are calling function startGame()?? – Bharti Sharma Dec 22 '16 at 14:09
  • oh thats just a button when the page loads that the user clicks, its running everything fine – kieron oates Dec 22 '16 at 14:12
  • implement a function called `insertAt(selector,position)` taking the selector and gets the content as text using `.text()' and insert your character at the position p and then redefine the content using `.text(newContent)` – CME64 Dec 22 '16 at 14:13
  • Where exactly do you want to append the letter ? – Manoj Lodhi Dec 22 '16 at 14:14
  • @CME64 could you show me with my code? i dont fully understand – kieron oates Dec 22 '16 at 14:18
  • @ManojLodhi in the array that has been created with all of the letters (for example "dog" would be turned into an array ["d", "o" , "g"]) and i want to insert the letters into the div where they should go – kieron oates Dec 22 '16 at 14:20

6 Answers6

3

Here is the working version of game :)

replaceAt function taken from here

var words = ['dog'];
var output = "";
var gRand = "";
var gWordAry = "";

function startGame() {
  var rand = words[Math.floor(Math.random() * words.length)]; //gets a random word from the array, stores as rand
  var wordAry = rand.split(''); //splits random word into its own array and each letter is in the array
  gRand = rand; //stores random word as global var
  gWordAry = wordAry;
  alert(wordAry);
  $('#hangmanGame').show();
  $('#startBtn').hide();
  //alert(rand);
  for (i = 0; i < wordAry.length; i++) { //draws a dash for every letter in the random word array after split
    //draw canvas dash
    output += ' _ ';
    $('#wordGuess').html(output);
  }


  //alert(output);


}
currentIndex = 0
function guess(letter) {
  var letterID = letter.toLowerCase(); //converts letter to lowercase from html
  //alert(letterID);
  var foundLetter = 0;
  for (i = 0; i < gWordAry.length; i++) {
    if (gWordAry[i] == letterID && gWordAry[i] !== '_') { //if a letter in the word array = the letter clicked this will run
      //alert('correct');
      if (currentIndex == i){
      foundLetter++;
      gWordAry[i] = '_'
      displayLetter(letterID, currentIndex++);
        
      break;
        }
    }
  }
  if (foundLetter == 0) { //if no letters in the array are found this will run
    alert('Try Again');
  }

}
String.prototype.replaceAt = function(index, character) {
  return this.substr(0, index) + character + this.substr(index + character.length);
}

function displayLetter(letterID,i) {
  //displays all letters in the word
  var toReplace = $('#wordGuess').html();


 $('#wordGuess').html($('#wordGuess').html().replaceAt($('#wordGuess').html().indexOf('_'), letterID))
}
startGame()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hangmanGame">
  <div id="wordGuess"></div>
  <table style="margin: auto;position: relative;top: 10px;">
    <tr>
      <td>
        <button class="alphabet" type="button"></button>
      </td>
      <td>
        <button type="button" onclick="guess('A')" id="1" class="alphabet">A</button>
      </td>
      <td>
        <button type="button" onclick="guess('B')" id="2" class="alphabet">B</button>
      </td>
      <td>
        <button type="button" onclick="guess('C')" id="3" class="alphabet">C</button>
      </td>
      <td>
        <button type="button" onclick="guess('D')" id="4" class="alphabet">D</button>
      </td>
      <td>
        <button type="button" onclick="guess('E')" id="5" class="alphabet">E</button>
      </td>
      <td>
        <button type="button" onclick="guess('F')" id="6" class="alphabet">F</button>
      </td>
      <td>
        <button type="button" onclick="guess('G')" id="7" class="alphabet">G</button>
      </td>
      <td>
        <button type="button" onclick="guess('H')" id="8" class="alphabet">H</button>
      </td>
      <td>
        <button class="alphabet" type="button"></button>
      </td>
    </tr>
    <tr>
      <td>
        <button class="alphabet" type="button"></button>
      </td>
      <td>
        <button type="button" onclick="guess('I')" id="9" class="alphabet">I</button>
      </td>
      <td>
        <button type="button" onclick="guess('J')" id="10" class="alphabet">J</button>
      </td>
      <td>
        <button type="button" onclick="guess('K')" id="11" class="alphabet">K</button>
      </td>
      <td>
        <button type="button" onclick="guess('L')" id="12" class="alphabet">L</button>
      </td>
      <td>
        <button type="button" onclick="guess('M')" id="13" class="alphabet">M</button>
      </td>
      <td>
        <button type="button" onclick="guess('N')" id="14" class="alphabet">N</button>
      </td>
      <td>
        <button type="button" onclick="guess('O')" id="15" class="alphabet">O</button>
      </td>
      <td>
        <button type="button" onclick="guess('P')" id="16" class="alphabet">P</button>
      </td>
      <td>
        <button class="alphabet" type="button"></button>
      </td>
    </tr>
    <tr>
      <td>
        <button type="button" onclick="guess('Q')" id="17" class="alphabet">Q</button>
      </td>
      <td>
        <button type="button" onclick="guess('R')" id="18" class="alphabet">R</button>
      </td>
      <td>
        <button type="button" onclick="guess('S')" id="19" class="alphabet">S</button>
      </td>
      <td>
        <button type="button" onclick="guess('T')" id="20" class="alphabet">T</button>
      </td>
      <td>
        <button type="button" onclick="guess('U')" id="21" class="alphabet">U</button>
      </td>
      <td>
        <button type="button" onclick="guess('V')" id="22" class="alphabet">V</button>
      </td>
      <td>
        <button type="button" onclick="guess('W')" id="23" class="alphabet">W</button>
      </td>
      <td>
        <button type="button" onclick="guess('X')" id="24" class="alphabet">X</button>
      </td>
      <td>
        <button type="button" onclick="guess('Y')" id="25" class="alphabet">Y</button>
      </td>
      <td>
        <button type="button" onclick="guess('Z')" id="26" class="alphabet">Z</button>
      </td>
    </tr>
  </table>
</div>
Community
  • 1
  • 1
asdf_enel_hak
  • 7,474
  • 5
  • 42
  • 84
  • This works but for words with 2 of the same letter it just puts it in twice in the same place and if you put letters in the wrong order it just puts it at the start rather than where it should go in the word – kieron oates Dec 22 '16 at 14:29
1

If you want all the letters that have been guessed to show up in your div, then you could modify displayLetter to first read what is in #wordGuessand append the letter that has just been guessed to that list, then write that information to #wordGuess.

BenM
  • 121
  • 7
1

Change your loop where you're building your blanks to wrap each underscore with an id specific to that index so you can target it later:

for (i = 0; i < wordAry.length; i++) { //draws a dash for every letter in the random word array after split
    //draw canvas dash
    output += "<span id='letter" + i + "'>_</span>";
}
$('#wordGuess').html(output);

When you're searching for where the matching letters are, pass the letter and the position you've found it in the word to the display letter function:

for (i = 0; i < gWordAry.length; i++) {
    if (gWordAry[i] === letterID) { //if a letter in the word array = the letter clicked this will run
        foundLetter++;
        displayLetter(letterID, i);
    }
}

Change your displayLetter function to take the index argument. Target the specific span with the id matching your index and set that to the given letter:

function displayLetter(letterID, index) {
    //displays all letters in the word
    $('#letter' + index).text(letterID);
}
C. Smith
  • 411
  • 2
  • 8
1

Probably a case of too many answers at this point, but here's how I would do it.

var answer = 'banana';
var state = '______';

function showLetter(letter, answer, state) {
  var lastPos = -1;

  while (answer.indexOf(letter, lastPos + 1) !== -1) {
    var position = answer.indexOf(letter, lastPos + 1);
    lastPos = position;
    state[position] = 'letter';
    state = state.substr(0, position)
      + letter
      + state.substr(position + 1);
  }

  return state;
}

This way you can pass your letter, answer, and state (with state being the current state of the guessed word) to this function and pass the result to something that will display it in the DOM for you. This could be as simple as: document.getElementById('wordGuess').innerHTM

I made a JSbin that shows the basic idea.

Sam Beckham
  • 1,218
  • 2
  • 12
  • 23
1

Based on @c-smith's approach, but slightly a robust one..

The working example can be seen here

First change your initialisation loop to.

for (i = 0; i < wordAry.length; i++) { //draws a dash for every letter in the random word array after split
                //draw canvas dash
                output += "<span class='letter" + wordAry[i] + "'> _ </span>";
                $('#wordGuess').html(output);
            }

and your displayLetter function changes to

function displayLetter(letterID){
            //displays all letters in the word
            $(".letter"+letterID).html(letterID);
            // return the number of letters found.
            return $(".letter"+letterID).length;
        }

and your guess function changes to this.

function guess(letter) {
            var letterID = letter.toLowerCase(); //converts letter to lowercase from html
            //alert(letterID);
            var foundLetter = displayLetter(letterID);
            if (foundLetter == 0){ //if no letters in the array are found this will run
                alert('Try Again');
            }

        }

I have tried to make it minimal.. but it can be improved alot more..

Minato
  • 4,383
  • 1
  • 22
  • 28
0

I hope this works for you

var words = ['dog', 'mouse', 'horse', 'fossil', 'christmas', 'mountain', 'javascript', 'glitter', 'pringles', 'connect'];
        var output = "";
        var gRand = "";
        var gWordAry = "";
        function startGame() {
            var rand = words[Math.floor(Math.random() * words.length)]; //gets a random word from the array, stores as rand
            var wordAry = rand.split(''); //splits random word into its own array and each letter is in the array
            gRand = rand; //stores random word as global var
            gWordAry = wordAry;
            alert(wordAry);
            $('#hangmanGame').show();
            $('#startBtn').hide();
            //alert(rand);
            for (i = 0; i < wordAry.length; i++) { //draws a dash for every letter in the random word array after split
                //draw canvas dash
                output += '_';
                
            }
          $('#wordGuess').html(output);


            //alert(output);


        }

function guess(letter) {
            var letterID = letter.toLowerCase(); //converts letter to lowercase from html
            //alert(letterID);
            var foundLetter = 0;
            for (i=0;i<gWordAry.length; i++){
                if (gWordAry[i] == letterID){ //if a letter in the word array = the letter clicked this will run
                    //alert('correct');
                    foundLetter++;
                    displayLetter(i);
                }
            }
            if (foundLetter == 0){ //if no letters in the array are found this will run
                alert('Try Again');
            }

        }

        function displayLetter(letterID){
            //displays all letters in the word
            //$('#wordGuess').append(letterID)
          //there is no need for the function I mentioned before ..
          var first = $('#wordGuess').text().substring(0,letterID);
          var second = $('#wordGuess').text().substring(letterID+1);
          $('#wordGuess').text(first+gWordAry[letterID]+second)
        }

startGame();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hangmanGame">
            <div id="wordGuess">  </div>  
            <table style="margin: auto;position: relative;top: 500px;">
                <tr> 
                    <td><button class="alphabet" type="button"> </button></td>
                    <td> <button type="button" onclick="guess('A')" id="1" class="alphabet">A </button></td> 
                    <td> <button type="button" onclick="guess('B')" id="2" class="alphabet">B </button></td>
                    <td> <button type="button" onclick="guess('C')" id="3" class="alphabet">C </button></td>
                    <td> <button type="button" onclick="guess('D')" id="4" class="alphabet">D </button></td>
                    <td> <button type="button" onclick="guess('E')" id="5" class="alphabet">E </button></td>
                    <td> <button type="button" onclick="guess('F')" id="6" class="alphabet">F </button></td>
                    <td> <button type="button" onclick="guess('G')" id="7" class="alphabet">G </button></td>
                    <td> <button type="button" onclick="guess('H')" id="8" class="alphabet">H </button></td>
                    <td> <button class="alphabet" type="button"> </button></td></tr>
                <tr> 
                    <td> <button class="alphabet" type="button"> </button></td>
                    <td> <button type="button" onclick="guess('I')" id="9" class="alphabet">I </button></td>
                    <td> <button type="button" onclick="guess('J')" id="10" class="alphabet">J </button></td>
                    <td> <button type="button" onclick="guess('K')" id="11" class="alphabet">K </button></td>
                    <td> <button type="button" onclick="guess('L')" id="12" class="alphabet">L </button></td>
                    <td> <button type="button" onclick="guess('M')" id="13" class="alphabet">M </button></td>
                    <td> <button type="button" onclick="guess('N')" id="14" class="alphabet">N </button></td>
                    <td> <button type="button" onclick="guess('O')" id="15" class="alphabet">O </button></td>
                    <td> <button type="button" onclick="guess('P')" id="16" class="alphabet">P </button></td>
                    <td><button class="alphabet" type="button"> </button></td></tr>
                <tr> <td> <button type="button" onclick="guess('Q')" id="17" class="alphabet">Q </button></td>
                    <td> <button type="button" onclick="guess('R')" id="18" class="alphabet">R </button></td>
                    <td> <button type="button" onclick="guess('S')" id="19" class="alphabet">S </button></td>
                    <td> <button type="button" onclick="guess('T')" id="20" class="alphabet">T </button></td>
                    <td> <button type="button" onclick="guess('U')" id="21" class="alphabet">U </button></td>
                    <td> <button type="button" onclick="guess('V')" id="22" class="alphabet">V </button></td>
                    <td> <button type="button" onclick="guess('W')" id="23" class="alphabet">W </button></td>
                    <td> <button type="button" onclick="guess('X')" id="24" class="alphabet">X </button></td>
                    <td> <button type="button" onclick="guess('Y')" id="25" class="alphabet">Y </button></td>
                    <td> <button type="button" onclick="guess('Z')" id="26" class="alphabet">Z </button></td> </tr>
            </table>
        </div>
CME64
  • 1,673
  • 13
  • 24