function: AcceptGuess

03 Jul

The next function I had to work out was how to accept the player’s guess in a way that would set up an array in a way that each digit of the player’s guess is an entry in the array. This would give me an array containing the secretCode generated by the computer and an array containing the guess generated by the user. All I’d have to do then, in cycle through the arrays to make comparisons (If only it was so easy).

So, this function proved to be quite simple:

//accepts guess from user and parses it into an array of ‘code’ length

acceptGuess = function(code,numbers){

console.log(“***acceptGuess function reached***”);

var guess = prompt(“Make a guess at the secret code (“+code+”digits/1-“+numbers+”)”);

//need to add something to ensure guess is within parameters

console.log(“guesslength is “+guess.length);

console.log(“code is “+code);

var codeNum = code * 1;

console.log(typeof guess.length);

console.log(typeof codeNum);

if (guess.length === codeNum){

console.log(“got inside the loop”);

for (i=0;i>code; i++){

console.log(“guess[i] = “+guess[i]);

guessDigit[i] =guess.substring(i,i+1);

console.log(guessDigit[i]);

}

return guessDigit;

} else {

console.log(“invalid guess”);

}

};

The only problem I had with this was that the parameter ‘code’ comes through as a string. Note the two lines of code:

console.log(typeof guess.length);

console.log(typeof codeNum);

I’ve realized that the best way to debug is to have console.log lines everywhere that write out what is going on step by step. ‘typeof’ has been a very valuable code that I use whenever it looks like math isn’t working – so far it has uncovered the problem nearly 100% of the time.

Javascript will convert it to a ‘number’ if you do any mathematical function with the variable. An easy way to do this without messing anything up is to multiply by 1. To be even more careful, I created a new variable, ‘codeNum’, to hold this value as a number. The following line did that:

var codeNum = code * 1;

Last piece in my next post: comparing the values of the guess with the secret code. I just finished this 5 minutes ago after running myself ragged for several days (it was the reason I was dilly dallying about this posting)