Created
June 11, 2014 07:18
-
-
Save stephanielingwood/773161ccee6de73fc303 to your computer and use it in GitHub Desktop.
NumberGuessingWithObjects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
keepPlaying = true | |
alert("Welcome to the Number-Guessing game! This is a two-person game. You can play against yourself, but it's more fun if you grab a friend to join you!"); | |
var name1 = prompt("Let's get started. Type the name of the first player here:"); | |
var name2 = prompt("Thanks. Now, type the name of the second player here:") | |
do { | |
alert("Okay, let's get ready to play. I'll choose a number between 1 and 10. Each of you will get to guess what it is. After you've both guessed, I'll tell you who was closer. First one to guess the number wins! Ready?"); | |
var guess1 | |
var guess2 | |
var answer = Math.ceil(Math.random() * 10); | |
function User(name, guess, howClose) { | |
this.name = name; | |
this.guess = guess; | |
this.howClose = howClose; | |
this.run = function() { | |
this.howClose = Math.abs(parseInt(this.guess) - answer); | |
} | |
} | |
user1 = new User(name1, guess1); | |
user2 = new User(name2, guess2); | |
while (user1.guess != answer && user2.guess != answer) { | |
guess1 = prompt(user1.name + ", please type your guess:"); | |
guess2 = prompt(user2.name + ", please type your guess:"); | |
user1.run(); | |
user2.run(); | |
if ( user1.howClose < user2.howClose ) { | |
alert(user1.name + " is closer."); | |
} | |
else { | |
alert(user2.name + " is closer."); | |
} | |
} | |
if (user1.guess == answer && user2.guess == answer) { | |
alert("You tied!"); | |
} | |
else if (user1.guess == answer) { | |
alert(user1.name + " won!"); | |
} | |
else if (user2.guess == answer) { | |
alert(user2.name + " won!"); | |
} | |
okResponse = true | |
do { | |
var playMore = prompt("Thanks for playing! Play again? Type yes or no."); | |
if (playMore === "yes") { | |
alert("Okay, let's play again!"); | |
okResponse = false | |
} | |
else { | |
alert("Have a great day, number-guessers!"); | |
okResponse = false | |
keepPlaying = false | |
} | |
} while(okResponse); | |
} while(keepPlaying); | |
</script> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment