Number Guesser Challenge Project (JavaScript)

Can you post your whole solution here?
If you are in the project, click in the top right corner on Tools and then “Create a Gist”

Your compare Guesses function seems to work.

Hi, thanks for the reply. I have done as asked and got a link for my whole code here:

Let me know what you find and thanks for the help. To reiterate the issue is:

Im having one issue with my code: When I select a number and click guess and the computer wins, everything in the app works as it should and the ‘New Round’ button activates. Where things go wrong is if I win. Nothing happens except the target number is shown. My ‘make a guess button’ is still blue and I actually have to keep pushing it until the computer wins again. So basically the games totally rigged for the computer to win lol.

Hey Korrin,

the issue is in the updateScore function.
case ‘human’ : humanScore = humanscore + 1;
The S should be capital.

How have i found it?
I have checked the developer console in my browser while running it. Turns out there was a reference Error logged:

Uncaught ReferenceError: humanscore is not defined
    at updateScore (script.js:25)
    at HTMLButtonElement.<anonymous> (game.js:33)

Why does it behave like it does?
When clicking the “Make a guess” Button the following function is called in game.js:

guessButton.addEventListener('click', () => {
  // Generate the target value
  target = generateTarget();
  // Retrieve the player's guess
  const currentHumanGuess = humanGuessInput.value;
  // Make a random 'computer guess'
  const computerGuess = Math.floor(Math.random() * 10);

  // Display the computer guess and the target
  computerGuessDisplay.innerText = computerGuess;
  targetNumberDisplay.innerText = target;
  
  // Determine if the human or computer wins:
  const humanIsWinner = compareGuesses(currentHumanGuess, computerGuess, target)
  const winner = humanIsWinner ? 'human' : 'computer'

  // Update the correct score:
  updateScore(winner);

  // Display the winner
  if (humanIsWinner) {
    guessButton.innerText = 'You Win!!!!!';
    guessButton.classList.toggle('winning-text')
  } else {
    computerWinsDisplay.innerText = 'Computer Wins!!!';
  }

  // winnerDisplay.innerText = humanIsWinner ? 'You win!' : 'Computer wins!';

  // Display the current scores:
  humanScoreDisplay.innerText = humanScore;
  computerScoreDisplay.innerText = computerScore;
  
  // Set the correct disabled state for the buttons
  guessButton.setAttribute('disabled', true)
  nextRoundButton.removeAttribute('disabled');
});

When the human is supposed to win, everthing is working fine in here until updateScore(winner) is called.
If this happens the interpreter throws a Reference Error exception. As this function does not catch the exception, the execution gets interrupted and nothing below updateScore(winner) is executed.

1 Like

Wow thanks for taking the time to check the code for me and provide that helpful article! Stumped by a capital letter hehe Well im happy the actual logic was correct and I can move onto my next lessons. Thanks a lot! :sun_with_face: :comet: :eight_pointed_black_star:

Hi y’all

Been having fun with this challenge, i tried to switch it up the last challenge by displaying and hiding the “guess” button with an “invalid input” button, i then added a ‘keyup’ listener to the humanInput field - was enjoyable :slight_smile: I made a bit of changes in the game.js file and added a button in the index.html.

if you can use it you can find my solution here:

https://github.com/MortenHusted/codecademy/tree/main/number-guesser

If any on you have any comments or suggestions as to how I can improve it, feel free to comment on it.
Best regards Morten

Hi Ben.
I made the same solutions as you at first. Although I would write your compareGuesses function like this:

const compareGuesses = (humanGuess, computerGuess, secretTarget) => {
if ((Math.abs(computerGuess - secretTarget)) < (Math.abs(humanGuess-secretTarget))) {
return false;
} else {
return true;
}
}

You really only need to check if the absolute difference from the computerGuess to secretTarget is smaller than the humanGuess to secretTarget :slight_smile:

/Morten

I found this really difficult I must say, I managed the random number function at the beginning, and the rest of the functions were partly right but I lost it when I had to figure out how to link the Math.abs with an if statement. At first I tried to make a separate function to accomplish the Math.abs and then use the argument from the function to calculate the score difference but i couldn’t reach the correct format. Did anyone else struggle to complete this?

good point! I was so focused on the logic that I didn’t see the simple solution

Absolute values may not come up until high school maths. Seems there is more to them than making a number positive. Not for now, though. Enough to know that with Math.abs() we make -3 into 3.

Subtraction is not commutative, meaning that changing the order will most likely change the outcome, in particular, the sign. A minus B is only equal to B minus A when A equals B.

This is where absolute value comes into play.

    |A - B| === B - A    //  true

Now the outcomes do equate.

To reiterate, it is not as simple as it appears. Took a few days of class time for students to wrap their heads around it when applied to maths. That’s all I remember.

Hello everyone. i am new to code academy and I am having an issue with the Number Guesser personal project. Not sure why my code returns a value of 1. Please advise?

let humanScore = 0;
let computerScore = 0;
let currentRoundNumber = 1;

// Write your code below:

const generateTarget = () => {

return Math.floor(Math.random() * 10);

}

const compareGuesses = (userGuess, computerGuess, targetNumber) => {
if (Math.abs(userGuess - targetNumber) < Math.abs(computerGuess - targetNumber)) {
return true;
} else if (Math.abs(computerGuess - targetNumber) < Math.abs(userGuess - targetNumber)) {
return false;
} else {
return true;

}
compareGuesses();
generateTarget();

const updateScore = (winner) => {
if (winner == ‘computer’) {
computerScore++;
} else if (winner == ‘human’) {
humanScore++;
}
}

updateScore(‘human’);
console.log(humanScore);

updateScore(‘computer’);
console.log(computerScore);
compareGuesses();
generateTarget();

const advanceRound = () => {
currentRoundNumber = currentRoundNumber + 1;
}
advanceRound();
updateScore();
compareGuesses();
generateTarget();

let humanScore = 0;
let computerScore = 0;
let currentRoundNumber = 1;

// Write your code below:
function generateTarget() {
    return Math.floor(Math.random() * 10);
};

//Which guess is closest to the target number
function compareGuesses(userGuess, computerGuess, targetNumber) {
    targetNumber = generateTarget();
    if(Math.abs(userGuess - targetNumber) < (computerGuess - targetNumber)) {
        return true;
    } else if (Math.abs(userGuess === targetNumber)) {
            return true;
        } else {
            return false;
        }
    }

//Increase the winner score after each round
function updateScore(winner) {
    if (compareGuesses === true) {
        humanScore++;
        return 'human';
    } else {
        computerScore++;
        return 'computer';
    }
}

//Update the round number after each round
function advanceRound() {
    currentRoundNumber++;
}

Can’t fix the problem! Is increasing the Computer score, the user score is not working! Someone can say what is the problem here?Thanks!

Here’s my codebyte for this project - I hope this helps some people!

let humanScore = 0; let computerScore = 0; let currentRoundNumber = 1; const generateTarget = () => Math.floor(Math.random() * 10) const checkNumberRange = (humanGuess) => { if (humanGuess < 0 || humanGuess > 9) { alert('MUST BE BETWEEN 0 AND 9!!!') } } const compareGuesses = (humanGuess, computerGuess, targetNumber) => { const humanDifference = Math.abs(targetNumber - humanGuess) const computerDifference = Math.abs(targetNumber - computerGuess) return humanDifference <= computerDifference // if (humanDifference > computerDifference) { // return false // } else if (computerDifference > humanDifference) { // return true // } else { // return true // } } const updateScore = (winner) => { if (winner === 'human') { humanScore++ } else { computerScore++ } } const advanceRound = () => { currentRoundNumber++ }

I actually just created new variables to sort out the Math.abs:

const compareGuesses = (humanGuess, computerGuess, targetNumber) => {
const humanDifference = Math.abs(targetNumber - humanGuess)
const computerDifference = Math.abs(targetNumber - computerGuess)
if (humanDifference > computerDifference) {
return false
} else if (computerDifference > humanDifference) {
return true
} else {
return true
}
}

1 Like

I also would highly recommend testing out your code on a different platform like repl :slight_smile:

Yep.Thanks!It works just fine!!!

Great work @objectsurfer53525 !

You can make your code a little more succinct by using the increment operator to increase the relevant variables by one for the functions updateScore() and advanceRound():

function advanceRound() {
currentRoundNumber++;
}

1 Like

Hi! I’m new here. I’m not entirely certain of how to run my code to see if it works. I don’t see any syntax errors in the code editor, but I’m not sure where to include it to see if the solution works with the other pieces of the project that I see in the download folder. Can someone help? I do think that something is incorrect in my code because I’m not seeing where the different pieces are being called. I hope that makes sense!

let humanScore = 0;
let computerScore = 0;
let currentRoundNumber = 1;

// Write your code below:
const generateTarget = () => {
  return (Math.floor(Math.random)) * 10
}
const compareGuesses = (humanGuess, computerGuess, targetNumber) => {
  const humanDifference = Math.abs(humanGuess-targetNumber)
  const computerDifference = Math.abs(computerGuess - targetNumber)
  if (humanDifference === computerDifference) {
    return true
  }
  else if (humanDifference > computerDifference) {
    return false
  }
  else if (humanDifference < computerDifference) {
    return true
  }
}
const updateScore = (theWinnerIs) => {
  if (compareGuesses = true) {
    humanScore + 1
  }
  else if (compareGuesses = false) {
    computerScore + 1
  }
}

const advanceRound = () => {
  currentRoundNumber + 1
}

Hello, @clm1234567, and welcome to the forums.

image
You should have the four files shown above. Your functions should be in the script.js file. The code that calls the functions you wrote is in the game.js file. To try out your code, and play the game, you simply need to open the index.html file in a web browser. Double clicking the file name should open it in your default browser, or you can right click the filename, and select the browser to open it with. To look for errors, open your browser’s console. Any error messages will be shown there.

Can you share links on how to test your code on other platforms?