Skip to content

Instantly share code, notes, and snippets.

@jargv
Created May 26, 2013 03:41
Show Gist options
  • Save jargv/5651645 to your computer and use it in GitHub Desktop.
Save jargv/5651645 to your computer and use it in GitHub Desktop.
* {
margin: 0;
padding: 0;
}
body {
margin: 30px auto;
width: 450px;
background-color: #efefef;
color: #35a;
font-size: 30px;
}
.main {
padding: 10px;
margin: auto;
width: 450px;
box-shadow: 0 0 5px black;
height: 100%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="guess.css" />
<script type="text/javascript" src="components/jquery/jquery.js"></script>
<script type="text/javascript" src="guess.js"></script>
</head>
<body>
<h1>J's Number guessing game</h1>
<div class="main">
<p id="message"></p>
<input id="guess" type="number" />
<input id="guessButton" type="button" value="guess" />
<input id="reset" type="button" value="start over" />
</div>
</body>
</html>
$(document).ready(function(){
//this tells the javascript engine to disallow certain constructs such as
//implicit globals. This is a good idea, but it's not needed
"use strict";
//get all the elements that we need from the DOM
var guess = $('#guess');
var message = $('#message');
var guessButton = $('#guessButton');
var actualNumber; //the number that the user will be guessing
start();
//when the user hits click the 'guess' button...
guessButton.on('click', function(){
//get the value of the guess element and parse it as an integer, base 10
var n = parseInt(guess.val(), 10);
checkGuess(n);
return false;
});
//when reset is clicked, call the start function. We don't keep the #reset
// element in a variable like we did with the other elements because we're
// not going to use it again.
$('#reset').click(start);
//check a guess and report back to the user. This is where all the logic is
function checkGuess(guess){
if (guess < actualNumber) {
setMessage("your guess is too low");
} else if (guess > actualNumber) {
setMessage("your guess is too high");
} else if (isNaN(guess)) {
setMessage("That's not a valid number...")
} else {
setMessage("YOU WIN! The number was " + actualNumber)
}
}
//display a message to the user
function setMessage(str){
//simply set the text in our message element
message.text(str);
}
//start or restart a game
function start(){
//Math.random gives us a floating point number between 0 and 1 (example:
// 0.5231). Then we multiply by 10 to get a floating point number between 0
// and 10 (example: 5.231). Then we use Math.round to round to an integer
// (example:5).
actualNumber = Math.round(Math.random() * 10);
setMessage("Guess a number between 1 and 10");
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment