Skip to content

Instantly share code, notes, and snippets.

@davidhaley
Created July 25, 2016 22:03
Show Gist options
  • Save davidhaley/8e09b0ea8da01101712b8722bce81354 to your computer and use it in GitHub Desktop.
Save davidhaley/8e09b0ea8da01101712b8722bce81354 to your computer and use it in GitHub Desktop.
"use strict";
$(document).ready(function() {
var form = document.forms[0];
var bet = document.getElementById("bet");
var guess = document.getElementById("guess");
var balance = 100;
var minBalance = 0;
form.addEventListener("submit", function(event) {
event.preventDefault();
if (balance <= minBalance) {
balance = 0;
alert("You have no money left!");
} else {
var betAmount = parseInt(bet.value);
var guessAmount = guess.value;
var randNumber = Math.floor((Math.random() * 10) + 1);
if (guessAmount == randNumber) {
balance += betAmount;
alert("Right on! Your new balance is " + balance);
}
else if (Math.abs(guessAmount - randNumber) == 1) {
alert("Close but no dice! Your balance is still " + balance);
}
else if (Math.abs(guessAmount - randNumber) > 1) {
balance -= betAmount;
alert("Haha, you lose! Your new balance is " + balance);
}
}
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="jquery-2.2.1.js"></script>
<script src="betting-game.js"></script>
</head>
<body>
<h1>Betting Game</h1>
<form>
<p>Place a bet between $5 and $10:</p>
<input type="text" name="bet" id="bet"><br>
<p>Guess a number between 1 and 10:</p>
<input type="text" name="guess" id="guess"><br><br>
<button type="submit" id="btn">Submit!</button>
</form>
</body>
</html>
@srsgores
Copy link

srsgores commented Aug 2, 2016

Javscript Feedback

Overall, good work here. Remember that your app currently allows the user to input any bet or value, regardless of whether it is an integer or not. I would highly advise performing both HTML and client-side validation via JavaScript. You can use the constraint validation API methods to change error messages, but that is more of an advanced topic.

Suggestions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment