Skip to content

Instantly share code, notes, and snippets.

@jakehawken
Last active August 29, 2015 14:02
Show Gist options
  • Save jakehawken/20739c8600b69ad14091 to your computer and use it in GitHub Desktop.
Save jakehawken/20739c8600b69ad14091 to your computer and use it in GitHub Desktop.
<script>
var name, age, truth, playAgain, yesOrNo, randomNumber, game, newGame, unoMas;
var game = function()
{
this.playCount = 0;
//takes yes/no input, sanitizes user input, returns yes or no
this.yesOrNo = function (input)
{
var output = input.toLowerCase();
while (output !== "yes" && output !== "no") //keeps re-asking you if you don't say Y or N
{
var output = (prompt("No, silly. Type 'yes' or 'no'")).toLowerCase();
}
return output;
}
//generates a random integer between a user-generated minimum and maximum
this.randomNumber = function (min, max)
{
return (Math.floor(Math.random() * max) + min); //min is added because Math.floor rounds down and
}
//main game
this.guessLoop = function(minimum, maximum)
{
var actual = this.randomNumber(minimum, maximum);
var guess = prompt("I'm thinking of a number between " + minimum + " and " + maximum + ". Guess it! (You get 3 guesses!)");
var i = 0;
while (guess <= maximum && guess >= minimum && i < 3)
{
if (guess != actual) //keeps re-asking you if you guess wrong
{
guess = prompt("Not quite. You were off by " + (Math.abs(actual-guess)) + ". Guess again.");
}
else //Don't need to specify the inverse condition
{
break;
}
i++;
}
if (guess == actual)
{
alert("Well done! You got it!");
}
else
{
alert("Sorry, you ran out of guesses!");
}
this.playCount++;
}
this.playAgain = function (min, max)
{
do {
var answer;
this.guessLoop(min,max);
answer = prompt("Would you like to play again? (Yes or No)");
answer = newGame.yesOrNo(answer);
this.playCount++;
}
while (answer == "yes");
alert("Thanks for playing! You played " + newGame.playCount + " times. As a reward, here's a rad website!");
window.open("http://www.jakehawken.com");
}
}
newGame = new game ();
name = prompt("Well hello there! What's your name?");
age = prompt("Hi, " + name + "! Pleased to meet you. How old are you?");
truth = prompt("Really? " + age + "? Is that your real age?");
truth = newGame.yesOrNo(truth);
if (truth == "yes")
{
alert("Ok, I believe you. Click OK or hit Enter to get started.");
}
else
{
alert("Well, that was a weird thing to lie about... Alright, let's get started.");
}
newGame.guessLoop(1,10);
unoMas = newGame.yesOrNo(prompt("Would you like to play again? (yes or no)?"));
if (unoMas == "yes")
{
newGame.playAgain(1,20);
}
else
{
alert("Thanks for playing! You played " + newGame.playCount + " times. As a reward, here's a rad website!");
window.open("http://www.jakehawken.com");
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment