Skip to content

Instantly share code, notes, and snippets.

@nw
Created March 25, 2015 03:20
Show Gist options
  • Save nw/45e47f7445d1b9cbe35d to your computer and use it in GitHub Desktop.
Save nw/45e47f7445d1b9cbe35d to your computer and use it in GitHub Desktop.
Hi Low Guess Game
$(function(){
var input = $('#guess')
, btn = $('#guess_btn')
, status = $('#guesses')
, reset = $('#reset');
var guesses = 0;
var aNumber = getRandom();
reset.on('click', function(){
guesses = 0;
aNumber = getRandom();
input.val("");
status.empty();
});
btn.on('click', function(){
var value = parseInt(input.val());
guesses += 1;
if(value === aNumber){
// game over
tellUser(guesses, value, "turns to guess");
} else if(value > aNumber) {
tellUser(value,"high");
// too high
} else {
tellUser(value, "low");
// too low
}
input.val("");
});
function tellUser(value, str, text){
var li = $('<li class="list-group-item" />');
if(!text){
text = "is too";
}
li.html("<b>"+ value + "</b> "+ text + " <b>" + str + "</b>");
status.prepend(li);
}
function getRandom(){
return Math.floor(Math.random() * 100);
}
});
<html>
<head>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
</head>
<body>
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<h3>Hi / Low Game</h3>
<hr />
<div class="form-group clearfix">
<label for="guess">Guess</label>
<input type="text" class="form-control" id="guess" placeholder="Enter guess">
<button class="btn btn-default pull-right" id="guess_btn">Guess</button>
</div>
<hr />
<ul id="guesses" class="list-group"></ul>
<button id="reset" class="btn btn-default">Reset</button>
</div>
</div>
<script type="text/javascript" src="hilow.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment