/*
Part II - UI
- Add jQuery to the page and change the game so that instead of using prompt and alert for I/O, it uses form fields and the DOM respectively.
- You can reference jQuery via any CDN, like Google's CDN.
- You will have to add a script tag inside your html <head> tag.
<head>
...
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
- Use this opportunity to experiment and get more comfortable with layout, CSS and even UI/UX.
*/
window.onload = function() {
$("#remaining_holdings").text(startingSum);
};
// Method: generate random integer.
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var startingSum = 100;
var remainingSum = startingSum;
var numberGuess = 0;
var currentBet = 0;
//
$("#submitGuessNumber").on("click", function(evt) {
evt.preventDefault();
//
currentBet = parseInt($("#betValueField").val());
if ((currentBet < 5 || currentBet > 10) && (currentBet > remainingSum)) {
console.log(parseInt(currentBet));
$("#betValueField").focus();
alert("Invalid bet: less than 5 or more than 10 or more than remaining holdings.");
return; //exit the entire method.
}
console.log("Current bet: $" + currentBet);
//
numberGuess = $("guessNumberField").val();
while (numberGuess < 1 || numberGuess > 10) {
numberGuess = parseInt(prompt("Please guess a number between 1 and 10 (inclusive)."));
}
console.log("parseInt guessed: " + numberGuess);
var randomNumber = getRandomInt(1, 10);
console.log("The random number is: " + randomNumber);
if (remainingSum > 0) {
if (numberGuess !== randomNumber) {
if (Math.abs(numberGuess - randomNumber === 1)) {
remainingSum = remainingSum;
console.log("Your total holdings remain as they were at " + remainingSum);
} else {
remainingSum -= currentBet;
console.log("Your total holdings " + (parseInt(remainingSum) + parseInt(currentBet)) + " have been reduced by " + currentBet + " to " + remainingSum + ".");
}
} else { //if the user guesses correctly.
remainingSum += currentBet;
console.log("Your total holdings " + (remainingSum + currentBet) + " have been increased by " + currentBet + " to " + remainingSum + ".");
}
$("#remaining_holdings").text(remainingSum);
} else {
alert("Game over. Your holdings have been reduced to 0.")
}
});