Created
July 25, 2016 22:03
-
-
Save davidhaley/8e09b0ea8da01101712b8722bce81354 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
"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); | |
} | |
} | |
}); | |
}); |
This file contains hidden or 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
<!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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
===
in JavaScript; your comparison can fail with certain inputs. Read about the difference between==
and===
hereparseInt
returnsNaN
when a string is passed. For example, tryparseInt("dadada")
.Suggestions
required
pattern
, andtype="number"
to help prevent user-submitted type errorsconst
,let
, and template strings to better manage state. See my example for an ES2015 implementation of the betting game