Quote:
Originally Posted by HungryChapstick
Say the user guessed correctly in their 1st or 2nd attempt, how would you get it to write, for example, "You guessed correctly on your 2nd attempt?"
|
If you use an array like this
Quote:
Originally Posted by Philip M
Code:
var arr = ["", "first", "second", "third", "fourth"];
|
then if you want to change the max allowed num. of guesses, you will have to edit the array as well as the variable containing the max allowed guesses
This example tells the user if each guess if too high/low or correct and on which guess without using arrays.
Code:
<p>Previous guesses:</p>
<p id="prevGuesses"></p>
<p>Total number of guesses: <span id="numGuesses"></span></p>
<div>
<button id="btnNewGame">New game</button>
</div>
<script>
document.getElementById('btnNewGame').onclick=startGame;
var prevGuessObj = document.getElementById('prevGuesses');
var numGuessesObj = document.getElementById('numGuesses');
var maxGuesses = 4;
function startGame(){
isGuessCorrect = false;
prevGuessObj.innerHTML = '';
numGuessesObj.innerHTML = '';
corrNum = Math.floor(Math.random()*10);
numGuesses = 0;
do{
var guessNum = getGuess();
if(guessNum != null){
numGuessesObj.innerHTML = ++numGuesses;
if(guessNum < corrNum){
prevGuessObj.innerHTML += 'Guess '+numGuesses+': '+ guessNum +' is too low <br />';
} else if(guessNum > corrNum){
prevGuessObj.innerHTML += 'Guess '+numGuesses+': '+ guessNum +' is too high <br />';
} else {
prevGuessObj.innerHTML += 'Guess '+numGuesses+': '+ guessNum +' is CORRECT!!';
isGuessCorrect = true;
}
}
}while(!isGuessCorrect && numGuesses < maxGuesses && guessNum != null)
}
function getGuess(){
do{
var guess = window.prompt('Guess a number','');
if(guess == null){return null;}
guess = parseFloat(guess);
}while(isNaN(guess))
return guess;
}
</script>
Instead of a window.prompt() for the guesses I would normally have an input textbox though.