mardi 2 février 2016

Javascript evaluate multiple conditions within while loop

The code below should keep asking the user for a randomly chosen musical instrument from an array until they get it right. It should count the number of guesses plus evaluate each guess and determine if it's alphabetically higher or lower than random. For some reasons my If statements don't seem to work properly. In example if I enter an item that is not on the list the code would not return the alert no.1 as expected. Even if the instrument is entered correctly, the code returns nothing instead of the the last alert as intended. Any help is greatly appreciated.

var MyInstrument;
var guess_input_text;   
var guess_input;
var finished = false;   
var guess_counter = 0;

function My_instrument()
{
        var instruments = ['violin', 'drums', 'pipe', 'harp', 'xylophone'];
        instruments.sort();
        var randomInstrument = Math.floor(Math.random()*instruments.length);
        MyInstrument = instruments[randomInstrument];

        while (!finished) {
            guess_input_text = prompt("I'm thinking of one of these instruments \n" 
            + instruments + "\n can you guess which one it is?"
            );
            var guess_input = instruments.indexOf(guess_input_text);
            alert(guess_input);
            guess_counter++;
            finished = check_guess();
        }
}

function check_guess() 
{
        if (guess_input == -1)
        {
          alert("you have not entered instrument from the list");
          return false;
        }

        if (guess_input != -1 && guess_input_text > MyInstrument)
        {
          alert("your instrument is alphabetically higher than mine");
          return false;
        }

        if (guess_input != -1 && guess_input_text < MyInstrument)
        {
          alert("your instrument is alphabetically lower than mine");
          return false;
        }

        alert("You got it! The instrument was " + target + 
              ".\n\nIt took you " + guess_counter + " guesses to get it!");
        return true;
}

My_instrument();

Aucun commentaire:

Enregistrer un commentaire