/* Number guessing game */ /* First lesson in javascript with MDN */ /* https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/A_first_splash */ let randomNumber = Math.floor(Math.random() * 100) + 1; /* Setup the constant field of HTML elements */ const guesses = document.querySelector(".guesses"); const lastResult = document.querySelector(".lastResult"); const lowOrHi = document.querySelector(".lowOrHi"); const message = document.querySelector(".message"); /* Input and button */ const guessSubmit = document.querySelector(".guessSubmit"); const guessField = document.querySelector(".guessField"); let guessCount = 1; let resetButton; /* Check the guesses */ function checkGuess() { // The main part of the guessing game const userGuess = Number(guessField.value); // Check the input // If the number is not within 1 and 100 (inclusive). if (userGuess<1 || userGuess>100) { message.textContent = `You have entered ${userGuess}. Enter a number between 1 and 100 (inclusive).` } else { message.textContent = ""; } // Write the previous guesses into the paragraph. if (guessCount === 1) { guesses.textContent = "Previous guesses: "; } // Append the current guesses. guesses.textContent = `${guesses.textContent} ${userGuess}`; // Check if the guess is the correct number. if (userGuess === randomNumber) { lastResult.textContent = "Congratulations! You got it right!"; lastResult.style.backgroundColor = "green"; lowOrHi.textContent = ""; setGameOver(); } else if (guessCount === 10) { lastResult.textContent = "!!!GAME OVER!!!"; lowOrHi.textContent = ""; setGameOver(); } else { lastResult.textContent = "Guess again!"; lastResult.style.backgroundColor = "red"; if (userGuess < randomNumber) { lowOrHi.textContent = "Last guess was too low!"; } else if (userGuess > randomNumber) { lowOrHi.textContent = "Last guess was too high!"; } } guessCount++; guessField.value = ""; guessField.focus(); } // Check for event guessSubmit.addEventListener("click", checkGuess); // Add the start new game button function setGameOver() { guessField.disabled = true; guessSubmit.disabled = true; resetButton = document.createElement("button"); resetButton.textContent = "Start new game"; // Place the button at the message message.textContent = ""; document.body.append(resetButton); // Add event listener to the start new game button resetButton.addEventListener("click", resetGame); } // Reset the game function resetGame() { guessCount = 1; const resetParas = document.querySelectorAll(".resultParas p"); for (const resetPara of resetParas) { resetPara.textContent = ""; } resetButton.parentNode.removeChild(resetButton); guessField.disabled = false; guessSubmit.disabled = false; guessField.value = ""; guessField.focus(); lastResult.style.backgroundColor = "white"; randomNumber = Math.floor(Math.random() * 100) + 1; }