Last active
August 29, 2015 14:02
-
-
Save manderly/4952c59d34acd1802343 to your computer and use it in GitHub Desktop.
Code Fellows Foundations 1 Homework Assignment 2: JavaScript guessing game prompts user to guess the current day of the year (out of 365)
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> | |
//global var set up | |
var debugMode = false; | |
var userGuess = 0; | |
var gameWon = false; | |
var triesUsed = 0; | |
var triesAllowed = 2; | |
var triesRemaining = triesAllowed; | |
var today = new Date(); | |
var daysSoFarThisYear = calculateDaysSoFarThisYear(); | |
while (triesUsed < triesAllowed && gameWon == false) { | |
promptForGuess(); | |
checkGuess(); | |
triesUsed ++; | |
triesRemaining = triesAllowed - triesUsed; | |
if (triesUsed == triesAllowed) { | |
outOfTries(); | |
} | |
} | |
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); | |
} | |
/* | |
Resources I used: | |
http://www.timeanddate.com/date/duration.html | |
http://www.w3schools.com/jsref/jsref_gettime.asp | |
http://www.w3schools.com/jsref/jsref_obj_date.asp | |
*/ | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Created for Code Fellows Foundations 1 Homework Assignment #2 ("guessing game")