Number Guesser Challenge Project (JavaScript)

To preserve code formatting in forum posts, see: [How to] Format code in posts

Here are a few issues to consider:

  • There needs to be a space between the return keyword and the value that you intend to return.
    Also, you must be careful with uppercase/lowercase.
    Math.random() is correct, but math.random() or MATH.random() will cause errors.
// You wrote:
returnmath.floor(math.random()*10);

// Change to:
return Math.floor(Math.random()*10);
  • I can’t view the instructions, but double-check whether compareGuess is the correct function name. Is it supposed to be compareGuess or compareGuesses? The function is supposed to return true/false, so its logic seems fine.

  • The updateScore function isn’t correct. The updateScore function needs to be given a parameter. It is expected that the argument passed to this function will either be the string "human" or the string "computer".
    Have a look at the game.js file. There you will find the following code:

const humanIsWinner = compareGuesses(currentHumanGuess, computerGuess, target)
const winner = humanIsWinner ? 'human' : 'computer'
updateScore(winner);

The compareGuesses function will return true/false which will be assigned to the humanIsWinner variable. Then based on this boolean value, the variable winner will either be assigned "human" or "computer". Then this string is passed as the argument to the updateScore function.
Therefore, your updateScore function should have a parameter to accept this argument.
Also, you will need to edit the condition accordingly,

// You wrote:
const updateScore = () => {
if (compareGuess() === true) {
...

// It should be: 
const updateScore = (winner) => {  
if (winner == "human") {
...
// The parameter name doesn't need to be named winner.
// If you think another name improves your code's readability, 
// you can choose that as the parameter name instead.
  • In advanceRound, you need to increment the variable currentRoundNumber.
// You wrote:
currentRoundNumber()++; 
// This is calling a non-existent function and 
// then trying to increment the return value.

// Instead, it should be:
currentRoundNumber++;
1 Like

Thank you so much!

So many of those were silly typos, I need to be more careful. But there was so much good guidance in here. Thank you.

1 Like

Hi,

Here is my completed project.

Many Thanks.

1 Like

Checkout my version here. Codecademy Challenge Project: Number Guesser

I completed the task my own way realising there were prompts to create certain functions. I made it responsive using CSS Grid and used Box Shadow too. Take a look if interested. :slight_smile:

2 Likes

I wonder why my Number Guesser output is not working with this code here??

This is my code:
let humanScore = 0;
let computerScore = 0;
let currentRoundNumber = 1;

const generateTarget = () => {
const random = Math.floor(Math.random() * 10);

if(random < 0 || random > 10) {
alert(‘Your guess is out of range’);
return generateTarget();
}
console.log(random);
return random;
}
const target = generateTarget();

const compareGuesses = (userGuess, computerGuess, targetNum) => {
const humanDifference = Math.abs(targetNum - userGuess);
const computerDifference = Math.abs(targetNum - computerGuess);

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

const advanceRound = () =>
currentRoundNumber++;

Hello guys! :wave:t2:
I’ve finished my project as well. It’s here:

And you can try it on the :green_circle: live site here:
https://marylag.github.io/number-guesser/

I want to validate human’s guess, but when I input a wrong value (negative values), I do not get the pop-up.

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

// Write your code below:

const generateTarget = () => Math.floor(Math.random() * 10);

const compareGuesses = (humanGuess, computerGuess, secretTarget) => {

  // validate user's input AKA guess in this context

  if (!(humanGuess < 0 || humanGuess > 9)) {
    alert('Input is out of range! Try again by inputing numbers between 1 and 9!');
  }

  const humanDifference = getAbsoluteDistance(secretTarget, humanGuess); // Math.abs(secretTarget - humanGuess);
  const computerDifference = getAbsoluteDistance(secretTarget, computerGuess);

  if (humanDifference > computerDifference) {
    return false;
  } else if (humanDifference < computerGuess) {
    return true;
  } 
}

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

const advanceRound = () => currentRoundNumber++;

const getAbsoluteDistance = (distance1, distance2) => {
  return Math.abs(distance2 - distance1);
}
if (!(humanGuess < 0 || humanGuess > 9)) { ...

The above says: If it is NOT the case that humanGuess is less than 0 or greater than 9, then the alert should be shown. In its present form, the alert will be shown whenever humanGuess is in the range 0-9.

You want the alert to be shown whenever humanGuess is not in the range 0-9 i.e.

if (humanGuess < 0 || humanGuess > 9) { ...
1 Like

I finished this challenge a few hours ago and have been looking at the project extensions. That got me looking into the other code files for this project. It looks like there is a small error in the game.js file, where handleValueChange function at the end of the code should disable the addButton for value greater than 8, not 9. Is this correct? Since the number being guessed is 0-9. The current code allows a user to select up to a value of 10.

I tried correcting and saving the game.js file myself, and I received a reference error for “document is not defined.” When I look into this, it seems this is usually due to server side rendering. I’m not yet familiar with all these intricacies, but is this simply due to the fact that Codecademy is serving the html rather than me accessing on my local computer? This seems to be an error that occurs a lot from using Next.js, from what I’ve read, so it seems it would make sense that Codecademy is using this or similar for their courses. Am I understanding this all correctly? Is there simply no way for me to save changes to this game.js file? That addButton issue will bother me until the day I die.

My version: Number Guesser

Features:

  • Limit of max number of rounds;

  • Created game results that will be shown after the game;

  • A bit changed HTML and CSS;

My script.js

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

const generateTarget = () => {
    return Math.floor(Math.random ()*10);
}

const getAbsoluteDistance= (currentHumanGuess,computerGuess,target) =>{
  if(currentHumanGuess < 0 || currentHumanGuess > 9) {
    alert('Your number is out of range! Please choose a number between 0 and 9. Good luck! )))');
  } else {
    const userResult=Math.abs(target-currentHumanGuess);
    const computerResult=Math.abs(target-computerGuess);
    const distance=computerResult-userResult;
    return distance;
  }
    }

const compareGuesses= (currentHumanGuess,computerGuess,target) => {
  const distance=getAbsoluteDistance(currentHumanGuess,computerGuess,target);
   return distance >=0;
}

compareGuesses(getAbsoluteDistance);
const updateScore= winner => {
return winner==='human'
?humanScore++
:computerScore++;
}

const advanceRound= () => {
  if(currentRoundNumber >=0 && currentRoundNumber <= 4) {
    currentRoundNumber++;
  } else if(currentRoundNumber >= 5) {
    gameOver();
  }
}

const gameOver = () => {
  const loseMessage=document.getElementById('lose');
  const winMessage=document.getElementById('win');
  const finalScoreW=document.getElementById('final-score-w');
  const finalScoreL=document.getElementById('final-score-l');
  if(humanScore>=3) {
    winMessage.style.display = 'block';
    finalScoreW.textContent= `Congratulations! Your score is ${humanScore}. The computer's score is ${computerScore}. If you want to restart the game, just reload the page.`;
  } else {
    loseMessage.style.display = 'block';
    finalScoreL.textContent= `The computer's score is ${computerScore}. Your score is ${humanScore}. If you want to restart the game, just reload the page.`;
  }
}
2 Likes

Hi,

Comparing the provided solution with my own: Number Guesser → I noticed that the user is able to press the “+”(add) button if the user number is already 9, which is something that I have been trying to fix but I just cannot do it. So when the user is on number 0, the “-”(substract) disappears but when the user is on number 9, the “+” does not disappear. I have taken each part of the code individually and I was not able to find a fix for this. This is also the default behavior in the provided solution

Anyone knows how this could be fixed?

Also I was wondering if anyone knows how the issue of data input could be fixed, for example: If I write the number 150 in the number guesser, the alert comes up (the alert that I set up that this input is not valid and it has to be between 1 and 9) but the game still runs, so no matter what, the user is losing that round because the alert does not stop the program from running. Same issue is in the provided solution that I linked just above.

My idea is to “force” the user to input a valid number otherwise the program does not run, so besides the alert also integrate something to block the program from running if the user types whatever number that is out of range. I found something called :out-of-range for CSS but it seems that this was not what I was looking for. Any solution on the JavaScript side?

Thanks in advance!