Вопрос

I have a non-marked brainstorming exercise to do which is related to a further marked coursework which will be similar but more complex. The task for the non-marked text-based Hangman is basically to create a JavaScript Hangman game that uses any of the four random words:

var words =["programming", "practical", "software", "development"];

The program should start by telling the user "Guess the word: _______ ; now the underscores represent the word to be guessed, which has to be one of the four above. The programm then asks the user to enter a letter, if it's right, the user will be told he still has 'ten go's' at the game and fills out one of the underscores. If not the user is told he is left with 9 go's and the underscores remain as they are.

I know how to ask the user for input - I am just really, really confused as to how to create the part of the programm where the 'Guess the word: _____-' is changed to "Guess the word: __I___" as for example.

What method do I have to use here? Any suggestions or generic examples would be really helpful! Thanks a ton!

Это было полезно?

Решение

At school we did the same but then in C#, if I remeber it correctly we did something like this :

        //this part creates the number of stripes depending on your word.
        //this part also breaks up the complete word into an array.
        var word = "programming";
        var letters = word.length;
        var loose_letters = new Array();
        var stripes = new Array();

        for(i = 0; i <= letters; i++)
        {
           stripes[i] = "_";
           loose_letters[i] = word.substring(i, i+1);
        }

now make something like a textbox where user can fill in the letter with a button

<input type = "text" id = "letter" name = "letter" />
<input type = "button" onClick="checkLetter();" value = "OK" id= "btn_OK" />

the checkLetter function :

function checkLetter()
{
   letter = document.getElementById("letter").value;

   for(i = 0; i < letters; i++)
   {
     if(letter == loose_letters[i])
     {
        stripes[i] = letter;
     }
     var complete_string += stripes[i]
   }     
}

I hope this helps, don't forget to add complete_string to the place where you want your people to see the outcome.

Другие советы

I'd use regular expressions.

var answer = "programmer";
var guessed = "aeiou";
var pattern = new RegExp("[^" + guessed + "]*", "gi");
var display = answer.replace(pattern, "_");

When they guess a letter, add it to guessed. You could use the length of guessed to see if they have turns left and display.indexOf("_") to see if they got the answer right.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top