1

I'm trying to replace the underscores in the underscore string with the corresponding letter from the word string (see full code in the snippet) and so far I'm getting weird bugs where it wont check all the underscores or will miss one, anyway to fix it? I'm happy to rebuild it if need be.

    var underscore = "";
    var letter;;

    var wordList = ["apple", "peach", "pear", "mango", "banana", "paper", "pens", "laptop", "desk", "chair", "star", "sky", "moon", "sun", "planets"];

    var word = wordList[Math.floor(Math.random() * wordList.length)];

    for (i = 0; i < word.length; i++)   {
        var underscore = underscore + "_ ";
    }    

   var replaceletter = 0
                for (i = 0; i < word.length; i++)   {
                    replaceletter = word.indexOf(letter, replaceletter);
                    underscore = underscore.replace(underscore.charAt(replaceletter), word.charAt(replaceletter));
                }

/* Hangman Game CSS File */
body
{
 background-color: #1B264F;
}

#main {
 background-color: #5386E4;
 height: 97vh; 
    width: 95vw;
    vertical-align: middle;

}
canvas {
    padding-left: 0;
    padding-right: 0;
    margin-left: auto;
    margin-right: auto;
    display: block;
    margin-top: auto;
    margin-bottom: auto;
}
<!DOCTYPE html>
<html>
 <head>
  <title>Hangman by Lachlan Teale</title> 
  <meta name="description" content="Lachlan Teale's Hangman Game 2015">
  <meta name="keywords" content="hangman, lachlan, teale, Javascript">
  <meta charset="UTF-8">
  <meta name="author" content="Lachlan Teale">
  <link rel="stylesheet" type="text/css" href="style.css">
 </head>
 <body>
 <canvas id="main" width="1920" height="1080" style="border:1px solid #d3d3d3;"></canvas>

 <script type="text/javascript">

 //setting variables
  var canvas = document.getElementById('main');
      var context = canvas.getContext('2d');
       var underscore = "";
       var letter;
       var complete = false;

 //list of words
  var wordList = ["apple", "peach", "pear", "mango", "banana", "paper", "pens", "laptop", "desk", "chair", "star", "sky", "moon", "sun", "planets"];

 //picking a random word from the list
  var word = wordList[Math.floor(Math.random() * wordList.length)];

 //print out the underscores for the number of letters
  for (i = 0; i < word.length; i++) {
   var underscore = underscore + "_ ";
  }

  context.font = '50pt Calibri';
       context.textAlign = 'center';
       context.fillStyle = '#E2E2E3';
       context.fillText(underscore, canvas.width * 0.5, canvas.height * 0.70);

    //correct letter text
       context.font = 'bold 30pt Calibri';
       context.textAlign = 'center';
       context.fillStyle = '#E2E2E3';
       context.text
       context.fillText("Correct Letters", canvas.width * 0.08, canvas.height * 0.05);

    //Wrong Letter text
       context.font = 'bold 30pt Calibri';
       context.textAlign = 'center';
       context.fillStyle = '#E2E2E3';
       context.text
       context.fillText("Wrong Letters", canvas.width - (canvas.width * 0.08), canvas.height * 0.05);

 //checking which button is pressed
  window.addEventListener('keydown', function(event) {
   if ( event.keyCode >= 65 && event.keyCode <= 90 ) {
       context.clearRect(0, canvas.height * 0.80, canvas.width, canvas.height);  
          letter = String.fromCharCode( event.keyCode ).toLowerCase();
          context.font = '50pt Calibri';
         context.textAlign = 'center';
         context.fillStyle = '#E2E2E3';
         context.fillText(letter, canvas.width * 0.5, canvas.height * 0.85);
        }
  });

 //checking if back key is pressed
  document.addEventListener('keydown', function(event) {                     
      if ( event.keyCode == 8 ) {              
       context.clearRect(0, canvas.height * 0.80, canvas.width, canvas.height); 
      }
     });

 //checking if enter is pressed
       document.addEventListener('keydown', function(event) {                     
      if( event.keyCode == 13 ) {
    //checking if letter is in the word
       var replaceletter = 0
          for (i = 0; i < word.length; i++) {
        replaceletter = word.indexOf(letter, replaceletter);
        underscore = underscore.replace(underscore.charAt(replaceletter), word.charAt(replaceletter));
       }

    context.clearRect(canvas.width * 0.4, canvas.height * 0.3, canvas.width *0.7, canvas.height * 70);
       context.font = '50pt Calibri';
         context.textAlign = 'center';
         context.fillStyle = '#E2E2E3';
         context.fillText(underscore, canvas.width * 0.5, canvas.height * 0.70);
   }
     });
  
  </script>
 </body>
</html>
MrTeale
  • 57
  • 1
  • 9

2 Answers2

0

You can replace them using this loop instead:

for (i = 0; i < word.length; i++) {
    underscore = underscore.replace("_", word.charAt(i));
}

There may be more elegant solutions to this, but I don't quite understand even if this is what you want.

Iulian Onofrei
  • 9,188
  • 10
  • 67
  • 113
-1

This is my first time posting in Stackoverflow. I've been looking for the same thing you are looking for, but couldn't find any. Then I made a solution of my own, and decided to help someone else.

I created my own function that is fairly simple and I hope this helps you. The function takes in 3 parameters:

Parameter 1: the letter or character you want to take its place
Parameter 2: the string itself
Parameter 3: the index of the letter you want replaced.

Here is the function:

function replaceAtIndex(character, word, index) {
    var tempStr = "";

    for (var n = 0; n < word.length; n++) {
        if (n == index) {
            tempStr += character;
        } else {
            tempStr += word[n];
        }
    }

    return tempStr;
}

What it basically does is create an entirely new string that is empty, and adds every letter from the original string to the new empty string one by one in order up until the index, and then adds the character you want to replace it instead at that index, and resumes the rest.

So how you would use this is like this:

var word= "abcdefg";
console.log(word); 
word = replaceAtIndex("z", word, 3);
console.log(word); 

Result:
abcdefg
abczefg

I hope this helps!

  • You're better off using [this solution](http://stackoverflow.com/a/1431113/865175) instead. No need to iterate over each character. – Iulian Onofrei Apr 11 '15 at 20:24