I am currently using HTML and Javascript to create a number guessing game. The issue with my current code is that any number the user inputs is a number that is ruled as the correct number. The problem is that the random number generator is not being recognized for some reason. The game is simply supposed to pick a number from 1-100 and the user has to keep guessing a number to match the randomly generated number. And it should be able to reset once you click the new game button. I am just wondering how to resolve the issues with my code and how to get my desired output. Here's my code: https://jsfiddle.net/qg0froam/
<!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>
================================================================================================================================
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 = document.getElementById("guess_input"); // 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() {
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.
}