Skip to content

Instantly share code, notes, and snippets.

@basir
Created December 6, 2019 13:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save basir/7948da490e5a674f4cfca0814a552f16 to your computer and use it in GitHub Desktop.
Save basir/7948da490e5a674f4cfca0814a552f16 to your computer and use it in GitHub Desktop.
Random-Number-Game
<!DOCTYPE html>
<html>
<head> </head>
<body>
<script>
const max = 5,
min = 1,
prevGuesses = [];
let secretNum = null,
guessNum = null;
const render = function() {
if (guessNum > secretNum) {
alert(`${guessNum} is too high. Previous guesses: ${prevGuesses}`);
} else {
alert(`${guessNum} is too low. Previous guesses: ${prevGuesses}`);
}
};
const play = function() {
secretNum = Math.floor(Math.random() * (max - min + 1)) + min;
while (getGuess() != secretNum) {
if (guessNum != 0) {
render();
}
}
alert(
`Congrats! You guessed the number in ${prevGuesses.length} guesses!`
);
};
const getGuess = function() {
let num = prompt("Enter a guess between " + min + " and " + max);
if (!isNaN(num)) {
num = Number(num);
if (num < min || num > max) {
alert(`Please enter a number between ${min} and ${max}.`);
guessNum = 0;
return 0;
} else {
prevGuesses.push(num);
guessNum = num;
return num;
}
} else {
alert("It is not a number!");
guessNum = 0;
return 0;
}
};
play();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment