Skip to content

Instantly share code, notes, and snippets.

@manderly
Created June 10, 2014 18:24
Show Gist options
  • Save manderly/87ffc152c419fff76991 to your computer and use it in GitHub Desktop.
Save manderly/87ffc152c419fff76991 to your computer and use it in GitHub Desktop.
Code Fellows Foundations 1 Number Guessing Game adapted into instantiated object with customizable "guesses allowed" property
<script>
var debugMode = false;
function Game(tries) {
this.triesAllowed = tries;
var userGuess = 0;
var gameWon = false;
var triesUsed = 0;
var triesRemaining = this.triesAllowed;
var today = new Date();
var daysSoFarThisYear = calculateDaysSoFarThisYear();
function calculateDaysSoFarThisYear() {
var year2014Begin = new Date('1/1/2014'); //Set year begin date
var before2014Msec = year2014Begin.getTime(); //Milliseconds 1/1/1970 to 1/1/2014
var allMsec = today.getTime(); //Milliseconds from 1/1/1970 to today
//Subtracting msec between 1/1/1970 and 1/1/2014 from msec between 1/1/1970 and today to get this year's millisecond total.
//Divide this year's milliseconds by 86400000 to convert to days
return Math.floor((allMsec - before2014Msec) / 86400000);
}
function promptForGuess() {
userGuess = prompt("Today is " + today.toDateString() +". There are 365 days in 2014. Which day are we on? \n\n Tries Remaining: " + triesRemaining + "\n\n Enter your guess: ");
}
function checkGuess() {
if (userGuess == daysSoFarThisYear) {
alert("Correct! We are on day " + daysSoFarThisYear + " of 365.");
document.write("You win! Refresh to play again.");
gameWon = true;
} else {
offByNumber = daysSoFarThisYear - userGuess;
alert("Incorrect! \n\n HINT: Your guess is off by " + offByNumber);
}
}
function outOfTries() {
alert("Out of tries! We are on day " + daysSoFarThisYear + " of 2014. \n\nYour answer: " + userGuess);
document.write("Game Over - Refresh to play again!");
}
//Debug cheat puts answer in console for testing purposes
if (debugMode == true) {
console.log("DEBUG CHEAT Days so far in 2014: " + daysSoFarThisYear);
}
while (triesUsed < this.triesAllowed && gameWon == false) {
promptForGuess();
checkGuess();
triesUsed ++;
triesRemaining = this.triesAllowed - triesUsed;
if (triesUsed == this.triesAllowed && gameWon == false) {
outOfTries();
}
}
}
var tries = prompt("Number of tries you'd like: ")
game = new Game (tries);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment