Reputation: 57
So i have a basic number guessing game and it works fine, however I would like someone to show me how i could display the number of attempted guesses at the end of the game. Also would it be possible to show previous guesses at the end of the game like this?
var canvas;
canvas = openGraphics();
var max;
max = 100;
var numberToGuess;
numberToGuess = 50; // will be changed to Math.floor( Math.random() * max ) + 1;
canvas.setFont("comic sans ms", "15px", Font.Bold);
canvas.drawString("Number Guessing Game!");
var guess;
guess = prompt( "Please input your guess 1-100" );
do {
// check previous guess and alert low/high message
if ( guess ) {
if ( guess > numberToGuess ) {
alert( "Your guess was too high: " + guess);
}
else if ( guess < numberToGuess ) {
alert( "Your guess was too low: " + guess);
}
}
guess = prompt( "Please input your guess 1-100" );
} while ( guess != numberToGuess );
alert( "You guessed correctly! " + guess );
canvas.paint();
Upvotes: 0
Views: 908
Reputation: 136114
Sure, just keep a running track of the guesses. You should consider storing the actual input along with an indicator of whether it was high or low.
Start by declaring an empty array before the main loop
var guesses = [];
After the user has made a guess, add a new item to the list wiith the value, and whether it was high or low
if ( guess > numberToGuess ) {
alert( "Your guess was too high: " + guess);
guesses.push({value:guess,direction:'HIGH'});
}
else if ( guess < numberToGuess ) {
alert( "Your guess was too low: " + guess);
guesses.push({value:guess,direction:'LOW'});
}
Then at the end you can do 2 things
guesses.length
guesses
to output what each incremental guess wasSo perhaps something along the lines of
canvas.drawString( "You guessed correctly! " + guess + " in " + guesses.length + " guesses");
for(var i=0;i<guesses.length;i++){
canvas.drawString("Guess #" + (i+1) + ": " + guesses[i].value + " was " + guesses[i].direction);
}
Live example: http://jsfiddle.net/3vjve7dL/
Upvotes: 1