Number Guesser Challenge Project (JavaScript)

Hi I’m new to all of this, including forum discussion, I was pretty confident about my code for this challenge, I’ve also included the alert for guesses out of range, but than I entered here and now looks like that my code is too short, I think I went too straight to the point. I want to know if it would has been more accurate to the market standards if I did all the calculations in separately variables like all.

let humanScore = 0; let computerScore = 0; let currentRoundNumber = 1; // Write your code below: function generateTarget () { return Math.floor(Math.random()*10) }; function compareGuesses (humanGuess, computerGuess, secretTarget){ if (humanGuess < 0 || humanGuess >= 10) { alert('Your guess is out of range set a number between 0 and 9'); } else { return Math.abs(humanGuess - secretTarget) <= Math.abs(computerGuess - secretTarget) }; }; const updateScore = (winner) => { switch (winner) { case 'human' : ++humanScore; break; case 'computer' : ++computerScore; break; } } const advanceRound = (advanceRound) => ++currentRoundNumber;

I would really appreciate any comment,
Best,
Erick

Looks good to me. Clear and concise. No need to use variables if they dont add clarity.

You could add comments to the functions which explain what they should do, the expected input parameters and the expected output. Also if your function may throw any exception this should be documented (not the case here). Many professional programmers use JSDoc to automatically create Documentation from their sourcecode comments:
https://jsdoc.app/about-getting-started.html

While this is overkill for such a simple script, commenting functions might be a good habit getting into.

Thanks a lot for your comments.
I will check jsdoc, I didn’t get to HTML yet so sounds confusing now.
And will definitely clarify my code with comments next time.
Best,
Erick

Hi, just noticed 2 problems with your code:

1-) your Math.random only outputs numbers from 0-8, you need to multiply it by 10.
I’m very beginner, but will try to explain why.

Math.floor always returns the largest integer less than or equal to ‘x’, so if the Math.random outputs for example 0.99999 (since the outputs for Math.random is 0 inclusive to 1 exclusive), and you multiply it to 9, Math.floor will transform 8.9999 to 8.

You can test this with:
console.log( Math.floor ( 0.999 * 9 ) );
console.log( Math.florr ( 0.999 * 10) );

2-) on your function compareGuesses, you need to compare absolute numbers. Put on both sides of your “if” comparison inside a Math.abs( ’ HERE ’ ) otherwise negative numbers that will come from guesses lower than the target will always loose.

Best,
Erick

i’m having trouble getting the advance round number to increase each round, i’ve looked at other peoples code and i seem to have the same code but it doesnt seem to be working. Below is the code for that particular part and above is the full code. Any help would be appreciated.

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

Hey srjam,

doublecheck the name of your compareGuess(es) function. The issue with your code isn’t that your advance Round is not working, you’r just not getting to that part of the game.

Also, you could make your compareGuesses function a little easier to read/understand by using the “<=” comparison operator.

Thank you so much riumequa, i must have read my code a hundred times and just didn’t see what i was doing wrong.

Below is s section of the solution code →
const compareGuesses = (humanGuess, computerGuess, targetGuess) => {

const humanDifference = Math.abs(targetGuess - humanGuess)

const computerDifference = Math.abs(targetGuess - computerGuess)

return humanDifference <= computerDifference;

}

I was wondering why the return line is so short whenever the instructions call for it to return either true or false, depending on scenario.

Because (humanDifference <= computerDifference) itself is a statement that can be either true or false. Returning this statement returns true if the humanDifference is smaller or equal than the computerDifference and false otherwise.

Does this make sense to you?

I was not aware of this, but that makes sense! Thanks!

Hi Everyone. This was how i solved the project and with a lot of help from everyone’s post in this thread. Any feedback for improvements would be much appreciated.

Thanks EVERYONE and CODEACADEMY!

Jason

Thanks very much for your input. Unfortunately I am so new to coding and java script it has left me a bi confused, not down to you I’m sure!

I added you code to see how it would behave, to console.log in the if statement- could you tell me how this debugs the code?
Also, how are we calling the input values and checking they work with LHS and RHS at the end of code if nothing happens in the game when I call them? I am totally unaware of what you mean so please explain how calling these input values at the end of the code is mean to impact the game (see my code below? the game stays blank when I call your functions, so how it is testing they work?)

  1. I changed the >= operator but the game seems to work less now
  2. I have added Math.abs() but it does not seem to having the desired effect, MDN isn’t shedding light on how to use in this context unfortunately
  3. Can you please give me an example of how I should be using Math.random in my code- as far as I am aware that all looks right but the way I learn is visual so an example from you as a version of my code would be helpful
  4. yes I think so, I have edited the inputs, but please could you give me a visual example of how I could alter my code, if it is incorrect?
    I don’t want to get stuck on this exercise for another week haha :frowning:
    I really appreciate your help and input whilst I am learning how 's and why’s :slight_smile:

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

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

const compareGuesses = (userGuess, computerGuess, secretNumber) => {
console.log("LHS: " + secretNumber - userGuess);
console.log("RHS: " + secretNumber - computerGuess);
if (secretNumber - userGuess > secretNumber - computerGuess) {
return Math.abs(true);
}
else {
return Math.abs(false);
}
}

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

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

LHS: 1
RHS: 4

The console.log() statements should help debugging the function as they provide you with a way to “look into it” while it is running (outputting variables, letting you known when a certain branch is run etc.). However, i’ve noticed that i missed parentheses around the secretNumber - user/computerGuess calculation. Missing those, the NaN (Not a Number) returned in the log might have confused more than helped.

Let’s do it by example, starting with your original function:

//Should return true if humanGuess is closer or equal as close to the target as computerGuess const compareGuesses = (userGuess, computerGuess, secretNumber) => { console.log("userGuess: " + userGuess + ", computerGuess: " + computerGuess + ", secretNumber: " + secretNumber); console.log("LHS: " + (secretNumber - userGuess)); console.log("RHS: " + (secretNumber - computerGuess)); if (secretNumber - userGuess >= secretNumber - computerGuess) { return true } else { return false } } //Tests for compareGuesses //Check if the function works when the guess closer to the target is bigger than the target console.log(compareGuesses(6,3,5)); //should return true console.log(compareGuesses(3,6,5)); //should return false console.log(compareGuesses(6,4,5)); //should return true //Check if the function works when the guess closer to the target is smaller than the target console.log(compareGuesses(4,7,5)); //should return true console.log(compareGuesses(7,4,5)); //should return false console.log(compareGuesses(4,6,5)); //should return true

Looking at the log, two things can be seen:

  1. The function only works when the guess closer to the target is smaller than the target.
  2. If we find a way to ignore the signs, we could just check if LHS <= RHS and return true if it is.

Here comes Math.abs() into play. Math.abs(5-4) and Math.abs(5-6) both return 1. So rewriting the function like that solves the issue:

//Should return true if humanGuess is closer or equal as close to the target as computerGuess const compareGuesses = (userGuess, computerGuess, secretNumber) => { if (Math.abs(secretNumber - userGuess) <= Math.abs(secretNumber - computerGuess)) { return true } else { return false } } //Tests for compareGuesses //Check if the function works when the guess closer to the target is bigger than the target console.log(compareGuesses(6,3,5)); //should return true console.log(compareGuesses(3,6,5)); //should return false console.log(compareGuesses(6,4,5)); //should return true //Check if the function works when the guess closer to the target is smaller than the target console.log(compareGuesses(4,7,5)); //should return true console.log(compareGuesses(7,4,5)); //should return false console.log(compareGuesses(4,6,5)); //should return true

Regarding Math.random() the MDN Page states “pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1)”. So the biggest number given by Math.random() is 0.9999999… This number times 9 gives 8.9999999999… Flooring it gives 8. So the biggest number returned by Math.floor(Math.random()*9) is 8. You need to multiply with 10 to get a range from 0 to 9.

Your updateScore function looks correct now. Making the changes in the compareGuess function and in generateTarget will solve all issues.

Hi Guys,
Please review my code and let me know is this correct or need any improvement.

I don’t think that lines 12, 37 - 50 is necessary.

Okay, Thanks for the suggestions.

Hi everyone im really loving this teaching app so far, ive tried other software in the past as well as self learning and just couldn’t grasp the concepts of the other language I tried to learn, but now im flying through these lessons, and really pleased as this is a skill ive always wanted so woop woop!

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.

I can only assume that {return true} is not actually returning true in the following code but returning unidentified maybe? It looks fine to me so what do you think? Thanks!

// determines who won the round const compareGuesses = (humanNum, computerNum, secretNum) => { let humanRemain = Math.abs(secretNum - humanNum); let computerRemain = Math.abs(secretNum - computerNum); if (humanRemain <= computerRemain) { return true } else {return false} }

^^ oh I just used the ‘create a code byte’ thing which I haven’t before but my code is in there once javascript is selected, can you all see that? Im not sure how everyone paste their code so it looks nice and formatted

UPDATE ok i wasn’t able to test the code in the app because there was no console or at least it wasn’t working but this one is. Ive tested the code, it should have returned true and it does. So im stumped as to whats causing the issue.

Here is my finished project! Any feedback/advice welcome. I am interested if there is a cleaner way I could have designed the compareGuesses function.

Thanks,

Ben

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.