-
Notifications
You must be signed in to change notification settings - Fork 0
/
numberguess.html
52 lines (43 loc) · 1.74 KB
/
numberguess.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Number Guessing</title>
</head>
<body>
<h1>Guess the magic number!</h1>
<input type="number" value=50 min=1 max=100 id="guessInput" autofocus=true>
<button id="guessButton" onclick="guess()">Guess</button>
<div id="resultDiv">Guess the magic number!</div>
<div id="historyDiv">Previous guesses: </div>
<script>
// first, get variables pointing to all relevant elements
let guessInput = document.getElementById("guessInput");
let guessButton = document.getElementById("guessButton");
let resultDiv = document.getElementById("resultDiv");
let historyDiv = document.getElementById("historyDiv");
// let the computer choose the magic number
let magicNumber = Math.floor(Math.random() * 100) + 1;
// this runs every time the button is clicked
function guess() {
// first, get the number that our player chose
let guessedNumber = guessInput.valueAsNumber;
// now compare whether it's below, above or equal to our magic number
if (guessedNumber === magicNumber) {
resultDiv.textContent = "you guessed right!!!";
// disable the guess button so the user can't guess any more
guessButton.disabled = true;
} else if (guessedNumber < magicNumber) {
resultDiv.textContent = "your guess is too low";
} else {
resultDiv.textContent = "your guess is too high";
}
// add the guessed number to the history
historyDiv.textContent += guessedNumber + " ";
// for convenience - move the focus back to the input
guessInput.focus();
}
</script>
</body>
</html>