Skip to content

Instantly share code, notes, and snippets.

@Jared-Prime
Created April 12, 2012 22:16
Show Gist options
  • Save Jared-Prime/2371404 to your computer and use it in GitHub Desktop.
Save Jared-Prime/2371404 to your computer and use it in GitHub Desktop.
Guessing Games - interactive object
// Codeacademy.com project, "Guessing Game"
// Simple interactive game, prompting the user to guess a number between 1 and 10, giving clues for the correct answer.
GuessingGame = function(min, max) {
this.init(min, max);
};
GuessingGame.prototype = {
minNumber: 1,
maxNumber: 10,
secretNumber: null,
lastMessage: null,
totalGuesses: 0,
init: function(min, max) {
this.minNumber = min || this.minNumber;
this.maxNumber = max || this.maxNumber;
this.generateNumber();
},
generateNumber: function() {
this.secretNumber = Math.floor(this.minNumber + (Math.random() * this.maxNumber));
},
guess: function(guess) {
this.totalGuesses++;
if(guess < this.secretNumber) {
this.message = guess + " is too low. Try again!";
return false;
}
else if (guess > this.secretNumber) {
this.message = guess + " is too high. Try again!";
return false;
}
else {
this.message = "Congratulations, " + guess + " is correct!";
return true;
}
}
};
var game = new GuessingGame();
var guessResult = false;
do {
var guessStr = prompt("Guess a number between " + game.minNumber + " and " + game.maxNumber + ":");
if(guessStr && !isNaN(guessStr)) {
var guessInt = parseInt(guessStr, 10);
guessResult = game.guess(guessInt);
console.log(game.message);
}
} while(false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment