I'm trying to keep track of how many guesses are made and then print that number when the correct number is guessed. The number of guesses isn't being updated when the wrong number is guessed, so it keeps showing up that it took only 1 guess, when it really took more.
let num = Math.floor(Math.random() * 20) + 1;
console.log(num);
let num_guess = 0
function do_guess() {
let guess = Number(document.getElementById("guess").value);
let num_guess = 1
let message = document.getElementById("message");
if (isNaN(guess)) {
message.innerHTML = 'That is not a number!';
}
else if (guess > 20) {
message.innerHTML = 'That number is not in range, try again.'
num_guess+=;
}
else if (guess > num) {
message.innerHTML = "No, try a lower number."
num_guess+=;
}
else if (guess < num) {
message.innerHTML = "No, try a higher number."
num_guess+=;
}
else if (guess == num) {
message.innerHTML = "You got it! It took you " + num_guess + " tries.";
}
}
<!doctype html>
<head>
<title>Higher - Lower</title>
</head>
<body>
<div class="container">
<h1>Higher Lower</h1>
<p>Guess a number between 1 and a maximum number of your choosing!</p>
<div class="row">
<div class="col-lg-3 col-md-6">
<form>
<div class="form-group">
<label>Your guess:</label>
<input type="text" id="guess" class="form-control">
</div>
<button type="button" class="btn btn-primary" onclick="do_guess()">Guess</button>
</form>
</div>
</div>
<p id="message"></p>
</div>
<script src="higherlower.js"></script>
</body>
```
let num_guess = 1
You are declaring the variable twice and each time the function is called, it will be set to 1.
num_guess+=; this won't increment the variable. See below.
let num = Math.floor(Math.random() * 20) + 1;
console.log(num);
let num_guess = 0;
function do_guess() {
let guess = Number(document.getElementById("guess").value);
let message = document.getElementById("message");
if (isNaN(guess)) {
message.innerHTML = 'That is not a number!';
}
else if (guess > 20) {
message.innerHTML = 'That number is not in range, try again.'
num_guess += 1;
}
else if (guess > num) {
message.innerHTML = "No, try a lower number."
num_guess += 1;
}
else if (guess < num) {
message.innerHTML = "No, try a higher number."
num_guess += 1;
}
else if (guess == num) {
message.innerHTML = "You got it! It took you " + num_guess + " tries.";
num_guess += 1;
}
}
Related
I'm creating a guess the number with limited guesses. I have add an incrementor to check the number of times a user submits an answer. Everything seems to work except the loop starts at the final iteration and the games ends on the first try.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="script.js" defer></script>
</head>
<body>
<div>Guess The Number</div>
<input type="text" id="input">
<button id="btn">Check Answer</button>
<p id="guesses" style="display: inline-block;"></p>
<p id="hint"></p>
</body>
</html>
const input = document.getElementById("input")
const btn = document.getElementById("btn")
const guesses = document.getElementById("guesses")
const rndmNum = Math.floor(Math.random() * 100) + 1;
btn.addEventListener('click', () => {
if(isNaN(input.value)){
input.value = "Please type a number"
} else{
const hint = document.getElementById("hint");
let i = 0;
while (i < 10){
if(input.value === rndmNum){
hint.innerHTML = "Congratulations, You guessed correctly!";
break;
} else if(input.value > rndmNum){
hint.innerHTML = "Too High";
} else{
hint.innerHTML = "Too low";
} i++; guesses.innerHTML = "You have guessed " + i + " times";
}
if(i === 10){
hint.innerHTML = "Game Over! The correct number was " + rndmNum;
}
}
})
I've tried changing the number in the while loop condition. I've tried moving the incrementor in and out of the loops function. I've also tried chatgpt to see if it would work. But no luck. I would really appreciate your help.
I think you're misunderstanding the while loop. The loop will run once for every instance of i from 1 to 10 then stop running when the condition in the while loop is false. Based on what you mentioned you don't want a loop at all but to store the number of guesses into its own variable and increase that variable until you reach your limit.
const rndmNum = Math.floor(Math.random() * 100) + 1;
let numberOfGuesses = 0;
btn.addEventListener('click', () => {
if (isNaN(input.value)) {
return input.value = "Please type a number";
}
const hint = document.getElementById("hint");
if (input.value === rndmNum) {
hint.innerHTML = "Congratulations, You guessed correctly!";
return;
} else if (input.value > rndmNum) {
hint.innerHTML = "Too High";
} else {
hint.innerHTML = "Too low";
}
numberOfGuesses++;
guesses.innerHTML = "You have guessed " + numberOfGuesses + " times";
if (numberOfGuesses === 10) {
hint.innerHTML = "Game Over! The correct number was " + rndmNum;
}
})
I believe this is what you were trying to accomplish. The reason why it's not working with the loop because it will run ten times with the click of the button once.
const input = document.getElementById("input")
const btn = document.getElementById("btn")
const guesses = document.getElementById("guesses")
const rndmNum = Math.floor(Math.random() * 100) + 1;
//keep track of guess count
let count = 0;
//event listner to check the users answer
btn.addEventListener("click", checkAnswer)
//this function will check for answers or display game over
function checkAnswer(){
if(count > 9){
hint.innerHTML = "Game Over! The correct number was " + rndmNum;
} else if(input.value == rndmNum){
hint.innerHTML = "Congratulations, You guessed correctly!";
} else if(input.value > rndmNum){
hint.innerHTML = "Too High";
} else {
hint.innerHTML = "Too low";
}
count++
guesses.innerHTML = "You have guessed " + count + " times";
}
I have some difficulties with my first number guessing "game" in JavaScript. Can someone have a look and guide me what I did wrong? Started with that language not that long ago..
Function is assigned to one button
<input id="box;" class="btn" ; type="button" value="Guess" onClick="check()">Click to start !
User (player) have to press the button, guess the number (1-10) within 3 attemps and then play again or not. Every attemp I do it says "number is higher" but at the end result is random, even if you chose 10.
var hiddenNum;
var attemps;
hiddenNum = Math.floor(Math.random() * 10);
hiddenNum = hiddenNum + 1;
attemps = 0;
function check(guess) {
window.prompt("Please enter the number between 1 and 10", "10");
if (hiddenNum == guess) {
window.alert("Congratulations! You guessed correctly !");
again = window.prompt("Would you like to try again? Enter Y or N.", "Y");
if (again == "N" || again == "n") {
window.alert("Thanks for trying. Goodbye.");
window.close();
} else {
window.alert("The number has been randomized.");
window.location.reload();
}
} else {
attemps = attemps + 1;
if (hiddenNum < guess) {
result = "lower";
} else {
result = "higher";
}
window.alert("Guess number " + attemps + " is incorrect. The number is " + result + ".");
}
if (attemps >= 3) {
window.alert("Sorry, you have run out of guesses! The number was " + hiddenNum);
again = window.prompt("Would you like to try again? Enter Y or N.", "Y");
if (again == "N" || again == "n") {
window.alert("Thanks for trying. Goodbye.");
window.close();
} else {
window.alert("The number has been randomized.");
window.location.reload();
}
}
}
You designed your check function to have a guess passed to it but you are just calling it without doing so. So all your comparisons are against undefined.
You are also using window.prompt to get the actual guess. What you need to do is save the value returned from the prompt into a variable and then compare it. Check the snippet.
var hiddenNum;
var attemps;
hiddenNum = Math.floor(Math.random() * 10);
hiddenNum = hiddenNum + 1;
attemps = 0;
function check() {
let guess = window.prompt("Please enter the number between 1 and 10", "10");
if (hiddenNum == guess) {
window.alert("Congratulations! You guessed correctly !");
again = window.prompt("Would you like to try again? Enter Y or N.", "Y");
if (again == "N" || again == "n") {
window.alert("Thanks for trying. Goodbye.");
window.close();
} else {
window.alert("The number has been randomized.");
window.location.reload();
}
} else {
attemps = attemps + 1;
if (hiddenNum < guess) {
result = "lower";
} else {
result = "higher";
}
window.alert(
"Guess number " + attemps + " is incorrect. The number is " + result + "."
);
}
if (attemps >= 3) {
window.alert(
"Sorry, you have run out of guesses! The number was " + hiddenNum
);
again = window.prompt("Would you like to try again? Enter Y or N.", "Y");
if (again == "N" || again == "n") {
window.alert("Thanks for trying. Goodbye.");
window.close();
} else {
window.alert("The number has been randomized.");
window.location.reload();
}
}
}
<input id="box;" class="btn" ; type="button" value="Guess" onClick="check()">Click to start
you need to assign the prompt
var hiddenNum;
var attemps;
hiddenNum = Math.floor(Math.random() * 10);
hiddenNum = hiddenNum + 1;
attemps = 0;
function check() {
let guess = window.prompt("Please enter the number between 1 and 10", "10");
if (hiddenNum == guess) {
window.alert("Congratulations! You guessed correctly !");
again = window.prompt("Would you like to try again? Enter Y or N.", "Y");
if (again == "N" || again == "n") {
window.alert("Thanks for trying. Goodbye.");
window.close();
} else {
window.alert("The number has been randomized.");
window.location.reload();
}
} else {
attemps = attemps + 1;
if (hiddenNum < guess) {
result = "lower";
} else {
result = "higher";
}
window.alert("Guess number " + attemps + " is incorrect. The number is " + result + ".");
}
if (attemps >= 3) {
window.alert("Sorry, you have run out of guesses! The number was " + hiddenNum);
again = window.prompt("Would you like to try again? Enter Y or N.", "Y");
if (again == "N" || again == "n") {
window.alert("Thanks for trying. Goodbye.");
window.close();
} else {
window.alert("The number has been randomized.");
window.location.reload();
}
}
}
<input id="box;" class="btn" ; type="button" value='guess'onClick="check()">Click to start!
User (player) have to press the button, guess the number (1-10) within 3 attemps and then play again or not. Every attemp I do it says "number is higher" but at the end result is random, even if you chose 10.
You should store the value from window.prompt. In your code, you just use guess in the parameter of the function as the value of window.prompt which is incorrect.
Syntax for window.promp:
result = window.prompt(message, default);
Also, I have shorten your codes and store the duplicate item in a function to make it a little bit less messy.
function smallcheck() {
let again = window.prompt("Would you like to try again? Enter Y or N.", "Y");
if (again.toUpperCase() == "N") {
window.alert("Thanks for trying. Goodbye.");
window.close();
} else {
window.alert("The number has been randomized.");
window.location.reload();
}
}
function check() {
let guess = window.prompt("Please enter the number between 1 and 10", "10");
console.log(guess)
if (hiddenNum == guess) {
window.alert("Congratulations! You guessed correctly !");
smallcheck()
} else {
attempts++;
if (hiddenNum < guess) {
result = "lower";
} else {
result = "higher";
}
window.alert("Guess number " + attempts + " is incorrect. The number is " + result + ".");
}
if (attempts >= 3) {
window.alert("Sorry, you have run out of guesses! The number was " + hiddenNum);
smallcheck()
}
}
Noticed you never declared 'result'. So I made that variable into a ternary operator to shorten up your code a little more. Also, I added template literals :)
let hiddenNum = Math.floor(Math.random() * 10);
//console.log(hiddenNum);
hiddenNum = hiddenNum;
let attempts = 0;
const nextRound = function () {
let again = window.prompt('Would you like to try again? Enter Y or N.');
if (again.toUpperCase() === 'N') {
window.alert("Thank's for trying. Later nerd");
window.close();
} else {
window.alert('Try to guess the new number, nerd.');
window.location.reload();
}
};
function check() {
let guess = prompt('Please enter the number between 1 and 10');
console.log(guess);
if (hiddenNum === guess) {
alert('Congratulations! You guessed correctly !');
nextRound();
} else {
attempts++;
let result = hiddenNum < guess ? 'lower' : 'higher';
alert(`Guess number is ${attempts} is incorrect. The number is ${result}.`);
}
if (attempts >= 3) {
alert(`Sorry, you have run out of guesses! The number was ${hiddenNum}`);
nextRound();
}
}
<div>
<input
id="box"
class="btn"
style="
display: inline-block;
border-radius: 2em;
box-sizing: border-box;
color: white;
background-color: blueviolet;
cursor: pointer;
"
type="button"
value="Guess"
onClick="check()"
/>Click to start !
</div>
This is quite a lengthy code, but i wish to have the user put in her inputs but is limited to 5 tries. Each time she enters a wrong number, it is being stored into an array. At the end of her 5 tries, all her guesses will be displayed in the text area that is created. Idk why my loop isn't working & i'm currently am unsure of loops for javascript. Help would be appreciated :) Run the code would help you better understand what I mean!
var randomNo;
function getRandomArbitrary(min, max)
{
return Math.random() * (max - min) + min;
}
function playFunction()
{
const message1 = document.getElementById("wrongInput");
const message2 = document.getElementById("wrongInput2");
var min = Number(document.getElementById("input").value);
var max = Number(document.getElementById("input2").value);
function inIt()
{
message2.innerHTML = "";
message1.innerHTML = "";
}
function validateInput(displayErrorElement, value)
{
let message;
if (value = "")
{
message = "empty";
} else if (isNaN(value))
{
message = "not a number";
}
if (message)
{
displayErrorElement.innerHTML = "Input is " + message;
displayErrorElement.style.color = "red";
return false;
}
return true;
}
function validateRange(displayErrorElement, min, max)
{
if (min > max)
{
displayErrorElement.innerHTML = "The input must be higher than the lowest number";
return false;
}
return true;
}
inIt();
if(!validateInput(message1, min)) return false;
if(!validateInput(message2, max)) return false;
if(!validateRange(message2, min, max)) return false;
console.log(min);
console.log(max);
randomNo = Math.floor(getRandomArbitrary(max, min));
console.log(randomNo);
console.log(randomNo);
}
values = [];
function guess()
{
var maxGuesses = 5;
var x;
var target;
for (let i = 0; i < 5; i++)
{
var guess = document.getElementById("guessField").value;
//output the msg
var output = document.getElementById("output");
if (guess == randomNo)
{
output.value = "You have guessed correctly! " + "(" + guess + ")";
return true;
}
else if (guess > randomNo)
{
output.value = "Number is too high! " + "(" + guess + ")";
return false;
} else {
output.value = "Number is too low! " + "(" + guess + ")";
return false;
}
if (x == 4)
{
output.value = "You have run out of tries!"
}
target = document.getElementById("output");
target.innerHTML = "The target number is " + randomNo;
x = document.getElementById("guessField");
values.push(x.value);
x.value = "";
}
}
function displayRecord()
{
document.getElementById("output").innerHTML = values.join("<br>");
}
Enter a smaller number<br>
<input id="input" type="text">
<span id="wrongInput"></span><br>
Enter a larger number<br>
<input id="input2" type="text">
<span id="wrongInput2"></span><br>
<button type="button" onclick="playFunction()">Play button</button>
<br>
<!-- guess the number -->
<label for="guess">Guess the number</label><br>
<input text="text" class="guessField" id="guessField">
<span id="guessMessage"></span>
<input type="button" onclick="guess()" value="Guess button"><br>
<p>Output area</p>
<textarea id="output" name="output" rows="5" style="width: 50%"></textarea>
The guess function should not have a loop. Since you add the guess to the values array, you can use that to keep track of how many guesses have been made and quit the game when values.length == 5;
Also note I append the messages with +=. Example output.value += "You ....
let values = [];
var randomNo;
function getRandomArbitrary(min, max)
{
return Math.random() * (max - min) + min;
}
function playFunction()
{
const message1 = document.getElementById("wrongInput");
const message2 = document.getElementById("wrongInput2");
var min = Number(document.getElementById("input").value);
var max = Number(document.getElementById("input2").value);
function inIt()
{
message2.innerHTML = "";
message1.innerHTML = "";
values = [];
document.getElementById("output").value = "";
}
function validateInput(displayErrorElement, value)
{
let message;
if (value = "")
{
message = "empty";
} else if (isNaN(value))
{
message = "not a number";
}
if (message)
{
displayErrorElement.innerHTML = "Input is " + message;
displayErrorElement.style.color = "red";
return false;
}
return true;
}
function validateRange(displayErrorElement, min, max)
{
if (min > max)
{
displayErrorElement.innerHTML = "The input must be higher than the lowest number";
return false;
}
return true;
}
inIt();
if(!validateInput(message1, min)) return false;
if(!validateInput(message2, max)) return false;
if(!validateRange(message2, min, max)) return false;
console.log(min);
console.log(max);
randomNo = Math.floor(getRandomArbitrary(max, min));
console.log(randomNo);
console.log(randomNo);
}
function guess()
{
var maxGuesses = 5;
if (values.length >= maxGuesses) return false;
var guess = document.getElementById("guessField").value;
document.getElementById("guessField").value = "";
values.push(guess);
//output the msg
var output = document.getElementById("output");
if (guess == randomNo) {
output.value += "You have guessed correctly! (" + guess + ")\n";
return true;
}
if (guess > randomNo)
{
output.value += "Number is too high! (" + guess + ")\n";
}
else {
output.value += "Number is too low! (" + guess + ")\n";
}
if (values.length == 5)
{
output.value += "You have run out of tries!\n"
output.value += "The target number is " + randomNo;
}
}
function displayRecord()
{
document.getElementById("output").innerHTML = values.join("<br>");
}
Enter a smaller number<br>
<input id="input" type="text">
<span id="wrongInput"></span><br>
Enter a larger number<br>
<input id="input2" type="text">
<span id="wrongInput2"></span><br>
<button type="button" onclick="playFunction()">Play button</button>
<br>
<!-- guess the number -->
<label for="guess">Guess the number</label><br>
<input text="text" class="guessField" id="guessField">
<span id="guessMessage"></span>
<input type="button" onclick="guess()" value="Guess button"><br>
<p>Output area</p>
<textarea id="output" name="output" rows="5" style="width: 50%"></textarea>
my main aim is to stop the program if the user guess the number 5 times OR when the user guess the correct answer, the program should end too.
function abc()
{
var guessbutton = document.getElementById("guessbutton");
var guess = document.getElementById("guess").value;
var maxtries = 5;
var count = 0;
var secret = 10;
while (count < 6)
{
if (guess == secret)
{
document.getElementById("feedback").innerHTML = "correct";
guessbutton.disabled=true;
break;
}
else if (guess > secret)
{
document.getElementById("feedback").innerHTML = "too high";
}
else if (guess < secret)
{
document.getElementById("feedback").innerHTML = "too low";
}
else
{document.getElementById("feedback").innerHTML = "max try";
guessbutton.disabled=true;
break;
}
count++;
}
}
the problem i am facing with this code is that it will continue even after 5 tries.
i am assuming the error is due to count++; not working correctly
this is my html code
<input id="guess" type="text" name="guess">
<button id="guessbutton" type="button" onclick="return abc()">Guess</button>
<p id="feedback"></p>
You need to get rid of the while loop. You are just looping without allowing the user to update the input textbox. You should be checking the count on every click.
var guessbutton = document.getElementById("guessbutton");
var count = 0;
var maxTries = 5;
var secret = 10;
function abc() {
var guess = Number(document.getElementById("guess").value);
count++;
console.log(count);
if (guess == secret) {
document.getElementById("feedback").innerHTML = "correct";
guessbutton.disabled = true;
} else if (guess > secret) {
document.getElementById("feedback").innerHTML = "too high";
} else if (guess < secret) {
document.getElementById("feedback").innerHTML = "too low";
}
if (count >= maxTries) {
document.getElementById("feedback").innerHTML = "max try";
guessbutton.disabled = true;
}
}
<input id="guess" type="text" name="guess">
<button id="guessbutton" type="button" onclick="return abc()">Guess</button>
<p id="feedback"></p>
I'm making a game of Guess the Number, and I want to test if a variable guess is greater than a variable difficulty. difficulty has been taken from my HTML page, and it is not comparing correctly with guess.
//Initialize variables for player guess, guess counter and previous guesses
var guess = 0;
var guessCount = 0;
var previousGuesses = [];
function startGame() {
//Calculate difficulty
var difficulty = document.getElementById("difficulty").value;
//Calculate secret number
var secretNumber = Math.floor((Math.random() * difficulty) + 1);
//Repeats while player has not guessed the secret number
while (guess != secretNumber) {
//Checks for Cancel button pressed
guess = prompt("Enter your guess: ");
if (guess == null) {
return;
}
//Checks for empty string/no input
else if (guess == "") {
alert("Please enter a number");
}
//Checks if previously guessed
else if (previousGuesses.includes(guess)) {
alert("You have guessed this number before. Please try a different number.");
}
else if (guess < 1) {
alert("Please enter a number between 1-" + difficulty);
}
//Checks if guess is higher than secretNumber
else if (guess > secretNumber) {
alert("Your guess is too high");
//Increments guess counter
guessCount++;
//Adds the previous guess to previousGuesses
previousGuesses.push(guess);
}
//Checks if guess is lower than secretNumber
else if (guess < secretNumber) {
alert("Your guess is too low");
//Increments guess counter
guessCount++;
//Adds the previous guess to previousGuesses
previousGuesses.push(guess);
}
//Checks for correct guess
else if (guess == secretNumber) {
//Increments guess counter
guessCount++;
//Checks for correct grammar - guesses or guess
if (guessCount > 1) {
alert("Congratulations, you guessed the correct number in " + guessCount + " guesses!");
}
else {
alert("Congratulations, you guessed the correct number in " + guessCount + " guess!");
}
}
}
//Resets variables to play again
guess = 0;
guessCount = 0;
previousGuesses = [];
}
body {
font-family: sans-serif;
text-align: center;
animation: background 10s infinite;
}
h1 {
margin-top: 48px;
margin-bottom: 48px;
animation: heading 10s infinite;
}
button {
height: 48px;
width: 250px;
font-size: 24px;
}
<h1>Guess the Number</h1>
<button onclick="startGame()">Start the Game</button>
<h2>Difficulty</h2>
<select id="difficulty">
<option value="10">Beginner</option>
<option value="50">Intermediate</option>
<option value="100">Hard</option>
</select>
Read this: key info
This code works, but I want something to happen: When the guess is greater than difficulty, I want to print "Please enter a number between 1-" + difficulty. However, when I change this code:
else if (guess < 1) {
alert("Please enter a number between 1-" + difficulty);
}
into this:
else if (guess < 1 || guess > difficulty) {...}
(EDIT: the above code is to find out if the guess is greater than difficulty)
then what happens is that EVERY guess except 1, difficulty and anything more than difficulty is alerted by Please enter a number.
How should I fix this?
You're comparing strings not numbers. Convert your strings into numbers.
else if (parseInt(guess) < 1 || parseInt(guess) > parseInt(difficulty))
Better way: Convert it directly after input and...
guess = parseInt(prompt("Enter your guess: "));
...get the difficulty value as number
var difficulty = parseInt(document.getElementById("difficulty").value);
//Initialize variables for player guess, guess counter and previous guesses
var guess = 0;
var guessCount = 0;
var previousGuesses = [];
function startGame() {
//Calculate difficulty
var difficulty = parseInt(document.getElementById("difficulty").value);
//Calculate secret number
var secretNumber = Math.floor((Math.random() * difficulty) + 1);
//Repeats while player has not guessed the secret number
while (guess != secretNumber) {
//Checks for Cancel button pressed
guess = parseInt(prompt("Enter your guess: "));
if (guess == null) {
return;
}
//Checks for empty string/no input
else if (guess == "") {
alert("Please enter a number");
}
//Checks if previously guessed
else if (previousGuesses.includes(guess)) {
alert("You have guessed this number before. Please try a different number.");
}
else if (guess < 1 || guess > difficulty) {
alert("Please enter a number between 1-" + difficulty);
}
//Checks if guess is higher than secretNumber
else if (guess > secretNumber) {
alert("Your guess is too high");
//Increments guess counter
guessCount++;
//Adds the previous guess to previousGuesses
previousGuesses.push(guess);
}
//Checks if guess is lower than secretNumber
else if (guess < secretNumber) {
alert("Your guess is too low");
//Increments guess counter
guessCount++;
//Adds the previous guess to previousGuesses
previousGuesses.push(guess);
}
//Checks for correct guess
else if (guess == secretNumber) {
//Increments guess counter
guessCount++;
//Checks for correct grammar - guesses or guess
if (guessCount > 1) {
alert("Congratulations, you guessed the correct number in " + guessCount + " guesses!");
}
else {
alert("Congratulations, you guessed the correct number in " + guessCount + " guess!");
}
}
}
//Resets variables to play again
guess = 0;
guessCount = 0;
previousGuesses = [];
}
<h1>Guess the Number</h1>
<button onclick="startGame()">Start the Game</button>
<h2>Difficulty</h2>
<select id="difficulty">
<option value="10">Beginner</option>
<option value="50">Intermediate</option>
<option value="100">Hard</option>
</select>
change else if (guess < 1 || guess > parseInt(difficulty))
to else if (parseInt(guess) < 1 || parseInt(guess) > parseInt(difficulty))
or change the type at the input
guess = parseInt(prompt("Enter your guess: "));
You can also use the built-in Number function. See how I fixed your code below:
difficulty = Number(difficulty);
guess = Number(guess);
Try applying this after your variables are declared and it should work!
Change to this should help:
else if (guess < 1 || guess > parseInt(difficulty)) {