Number Guessing Game
You have to guess a number between 1-100.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Homework 6</title>
<script src="hw06.js"></script>
<link rel="stylesheet" href="hw06.css">
</head>
<body onload="newgame()">
<h1>High-low guessing game</h1>
<div id="controls">
<button onclick="newgame()">New game</button>
<form onsubmit="guess(); return false;"><input id="guess_input" type="number">
<input type="submit" value="Guess"></form>
</div>
<br><br>
<div id="output"></div>
</body>
</html>
CSS
html {
display: table;
margin: auto;
}
body {
display: table-cell;
vertical-align: middle;
font-family: Verdana, Geneva, Tahoma, sans-serif;
}
#output {
width: 450px;
height: 300px;
overflow-y: auto;
border: 4px solid black;
border-radius: 8px;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19)
}
form {
display: inline;
}
button, input {
border-radius: 8px;
}
h1 {
text-align: center;
}
#controls {
display: flex;
justify-content: space-evenly;
}
.victory {
font-size: 1.5em;
}
JavaScript
var output; // Global variable to reference the div element with id "output"
var answer; // This is the answer
var guessCount = 1; // This variable counts the number of guesses
var x; // This is the number guessed by the user
// Function that returns a random number in [minVal, maxVal].
function randomNumber(minVal, maxVal) {
return minVal + Math.floor(Math.random() * (maxVal - minVal + 1));
}
// Function that writes a message to the output div
function writeOutput(message) {
if (!output) {
output = document.getElementById("output");
}
output.innerHTML = message + "<br>" + output.innerHTML;
}
// Function that starts a new game
function newgame() {
writeOutput("I'm thinking of a number between 1 and 100...");
var answer = Math.floor(Math.random() * 100 + 1);
var guessCount = 0;
// TODO: use the randomNumber function to pick an answer for this game.
}
// Function that checks the player's guess against the answer
function guess() {
var guessCount = 1;
if(x == answer)
{
writeOutput("Congratulations! You guessed the number correctly! "
+ guessCount + " Guesses ");
}
else if(x > answer) /* if guessed number is greater
than actual number*/
{
guessCount++;
writeOutput("The guess is incorrect! Try a lower number");
}
else
{
guessCount++;
writeOutput("The guess is incorrect!! Try a higher number")
}
// TODO: look at the value of guess_input, compare it with the answer, and
// tell the player whether the guess is too low, too high, or correct.
}