Lesson 3 - Learning construction - Step 4

by nathanesa

HTML

<img src="https://cdn-www.bluestacks.com/bs-images/logo225.png"><br><br>

<form>
  <label>Enter Number:</label>
  <input id="userGuess" type="number" value="0" maxlength="4" size="4" >
</form>

<br>
<button onclick="runGuess()" id="button">confirm </button>
<br>
<br>
<p id="output">Enter a number between 1 and 20</p>

CSS

body {
  color: #665544;
  background-color: #2dabf9;
  font-family: Georgia, "Times New Roman", serif;
  text-align: center;
}

label, button {
  font-family: arial;
  color: white;
  font-size: 20px;
}

input {
  margin: 20px;
  font-size: 20px;
  width: 40px;
}

p {
  background-color: white;
  padding: 30px;
  border-radius: 10px;
  width: 250px;
  margin: 0 auto;
  font-size: 20px;
}

button {
  background: #2079c9;
  border: 0px solid #556699;
  border-radius: 11px;
  box-shadow: 0 0px #444444;
  padding: 10px 20px;
  color: #ffffff;
  display: inline-block;
  font: normal normal 20px/1 "Open Sans", sans-serif;
  text-align: center;
}

JavaScript

// computer picks random number between 1 and 20
let number = (Math.floor(Math.random() * 20) + 1);
let numberOfGuesses = 0;

function resetGame() {
  window.location.reload(1);
}

function tryAgain() {
  document.getElementById("output").innerHTML = 'Try again.';
}

function runGuess() {
  numberOfGuesses = numberOfGuesses + 1;
  let guess = document.getElementById('userGuess').value;
  
  if (number < guess) {
    document.getElementById("output").innerHTML = 'Too high.';
    setTimeout(tryAgain, 1000);
  } else if (number > guess) {
    document.getElementById("output").innerHTML = 'Too low.';
    setTimeout(tryAgain, 1000);
  } else {
    document.getElementById("output").innerHTML = 'You got it! It took you ' + numberOfGuesses + ' guesses.';
    setTimeout(resetGame, 2000);
  }
}