Number Guesser Challenge Project (JavaScript)

There are a few questions in your post - I’ll try to answer as much as I can and perhaps others can fill in the gaps. If you can share your entire code base via github or paste it here it will make things easier for myself and others to understand.

An important thing to note is X=X++ is NOT a valid expression. You can try it out on its own (using console logs) it doesn’t behave as you might expect. The appropriate way to use this shorthand syntax is to just use the experssion X++ which says take X and add 1 to it and then store it back to X or it means X=X+1. There is no need to assign X++ to X;

I think try the code without using the X++ shorthand and I believe your scores should update correclty.

In regards to the return statement. In this specific case you don’t need a return statement because you’re not trying to get the the function to return something and use it elsewhere. Here, the function is updating 2 global variable (variables that were declared outside the function) and so all updates you do in this function will hold and no explicit return value is needed since you’re not using the return value for anything.

I hope this helps! if you have any questions - feel free to reply and I’ll answer as best as I can.

Dear Bade,

That helps a lot!
I want to confirm that I understand correctly:
X=X+1 is acceptable, while X = X++ isn’t (although they supposedly look to us as the same).
And is it that the variables being in the global scope is the reason that return is unnecessary? Is it just unnecessary or redundant to use return in such a case? or, does it also cause the problem of not updating the score and round number?
Below are my codes (the corrected above, and the wrong one below).

Thank you so much for your help,
Sharon.

My code corrected (and running):

My code, before the corrections:

let humanScore = 0;

let computerScore = 0;

let currentRoundNumber = 1;

// Write your code below:

//Generate a random number from 0-9

const generateTarget = () => {

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

}

// Uses absolute numbers to decide whether human or computer guessed number is closer to target number (or if even).

const compareGuesses = (humanNum, computerNum, secretNum) => {

return Math.abs(secretNum - humanNum) <= Math.abs(secretNum - computerNum) ? true : false;

}

// Depending on the wonner in the guessing game, increases score of human or computer

const updateScore = (winner) => {

return winner ===‘human’ ? humanScore = humanScore ++ :

computerScore = computerScore ++;

}

// Counts the number of rounds played

const advanceRound = (currentRoundNumber) => {

currentRoundNumber = currentRoundNumber ++;

}

Yes that’s absolutely correct. If you want to use the shorthand then you can simply input X++ which will yield the same result as X=X+1.

Yes exactly!

You will run into problems in this scenario because generally speaking, you can only have 1 return value per function. In this exercise and so far in the course we’ve only seen how to return a number, string, bool or similar. So a return statement that returns 2 numbers or 2 simple variables is not valid. Also, the return is not being assigned to anything. If you want a return value from a function, you usually assign it to a variable and then use it elsewhere. Otherwise, if you’re updating global variables, there’s no explicit reason for a return - unless you’re doing some kind of error checking with the return value.

Later I believe we’ll see examples or where you can return an object or array that can hold multiple values.

Glad to help, if you any need anything else don’t hesitate to mention or message :))

Bader

I’m getting this error when I inspect my page:
Uncaught ReferenceError: generateTarget is not defined
at HTMLButtonElement. (game.js:18)

I’m able to run my code in the CodeAcademy editor and the code worked fine - I was able to play the game as expected. But I used the Visual Editor and opened the code by launching http-server, and am unable to click on the “Make a Guess” button.
This error also occurs when I run the code solution provided by CodeAcademy on my localhost.

Am I missing something?

Here’s my solution to this project!

Hope it helps anyone in trouble! Sometimes you just need to see a glimpse of how a solution is implemented to start thinking out of the box in some logical problems. Feel free to ask or comment!!

I’m really struggling with this project and didn’t understand the suggestion to use Math.abs(), so I took a look at the source code for the example project and am now even more confused.

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, targetGuess) => {
  const humanDifference = Math.abs(targetGuess - humanGuess)
  const computerDifference = Math.abs(targetGuess - computerGuess)
  return humanDifference <= computerDifference;
}

What I’m most hung up on is, how is targetGuess getting assigned to a number value? It hasn’t been defined, so why isn’t is NaN or something? I feel like the number should be coming from generateTarget();, but they’re not connected in any way…

Thanks in advance… m(_ _)m

Find the call to compareGuesses. Does it have three arguments? They get assigned to the three parameters, in the same order. targetGuess will be a reference to the third argument.

Hi, mtf. Thanks for taking the time to comment.

Right, targetGuess is the third parameter.
But how do these parameters get assigned an actual numerical value so the mathematical operation can take place?
I feel like I’m missing something obvious, but I have no idea where the numbers are coming from to do the math.

1 Like

Did you locate the line where the function is called from? Check both programs. Don’t change anything, just examine the line. Paste it in your reply, please, once you find it.

Parameters are defined by the values we assign to them in a function call.

const foo = function (x) {
    return x
}

Above, x is the parameter of the foo function. In its present state it is still undefined.

console.log(foo(42))    //  42

Above, we call the function with argument, 42. That is when x gets defined within the function context. If it was not defined, it could not have been returned as any value other than undefined.

1 Like

Sorry for still not understanding… what do you mean when you say both programs?
I also don’t understand what you mean by where the function is called from.

The sample of code that I included in my first post is all the code I currently have.
I imagine that the humanGuess is assigned a numeric value when the user enters a number into the game, but how does JavaScript understand that computerGuess should be a numeric value and not a string?

If this is the same project I’m thinking it is, there are two files, one of which is ‘game.js’. Am I correct?

The way the assignment is set up is somewhat “watered” down in the sense that they’ve placed part of the program in script.js which they expect the student to edit, but they also perform calls of these functions to target the elements on the page from the game.js file.

We were told NOT to modify game.js to get everything working as intended. But feel free to inspect it

If you look at line 1 of game.js file, they have declared a target variable.

Then on line 18, they use the function that we created in ‘script.js’ to generate the value of target variable.
target = generateTarget();

Then on line 29, they use compareGuess and pass target as the third parameter. So, this is where they’re getting the targetGuess from.

// Determine if the human or computer wins:
  const humanIsWinner = compareGuesses(
    currentHumanGuess,
    computerGuess,
    target
  );

In the script.js file we’re setting up all the functions but some if not all are being called from ‘game.js’ file.

Hope this helps!

Completed Number Guesser project including additional challenges

First time using gist.github so hopefully works :slight_smile: only issue with the code is the program still runs even after the alert saying the number needs to be between 0 and 9, anyone else have or work around this?

Hello everyone! I remade this number guesser project and these are the files for now. I will update this post ever so often to update the files with the newest version. Feedback is always appreciated, and have a good day!

:compass: CyanicalCoder

https://drive.google.com/drive/folders/1MIG-y_O-ueXBXo7mTl5eCHNBBC0CiM1d?usp=sharing

(I shared it as a Drive folder link since it contains several files that I either modified or created.)

Hi!
Must say this project is does give you a wake up call of what you really know how to do or not.
Only gripe I would have is the vague instructions (or I have reading comprehension issues) of which function/parameter names has to be precise to plug in the codes to game.js It took me a while to work that out, and I still don’t have a clear idea of how everything links up with the game.js side yet.

Second thing that I am wondering if it’s just me whom is missing the gist quick link button at the bottom of the console menu, I only have the ‘copy to clipboard’ and ‘reset project’ buttons there.

And finally, I think there is something fishy in my codes, most likely from the window.alert() (not sure to call this a function or method or something else) : Each time I reset the game.js and play the first round, the computer automatically gets one win regardless of whom won the first round. Not sure how to build around that.
Below is my codes:

Blockquote

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

// Write your code below:

const generateTarget = () => {
return Math.floor(Math.random() * 10);
}
console.log(generateTarget());
//test generateTarget function output

const getAbsoluteDistance = (a,b) => Math.abs(a-b);
console.log(getAbsoluteDistance(3,1));
// testing getAbsoluteDistance function, should return 2
const compareGuesses = (humanGuess,computerGuess,targetGuess) => {
if ((humanGuess < 0) || (humanGuess > 9)) {
window.alert(‘There is no way you could win when you are guess beyond the number range.’);
}
else if ((getAbsoluteDistance(humanGuess,targetGuess)) <= (getAbsoluteDistance(computerGuess,targetGuess))) {
return true;
} else {
return false;
}
}
const updateScore = (winner) => {
if (winner === ‘human’) {
return humanScore++;
} if (winner === ‘computer’) {
return computerScore++;
}
}

const advanceRound = () => {
currentRoundNumber++;
}
updateScore(‘human’);
console.log(humanScore); // To confirm that this value increased by 1
updateScore(‘computer’);
console.log(computerScore); // To confirm that this value increased by 1
console.log(compareGuesses(1,1,1));
//Tie game, should return true
console.log(compareGuesses(1,5,1));
// human won, should return true
console.log(compareGuesses(5,1,1));
//computer won, should return false
console.log(compareGuesses(14,9,1));
//should return with alert

Yeah I think it was intended this way (as far as I can tell). Here’s some modifications I’ve done and posted on github. You can download and take a look. I’ve made adjustments to the game.js file to not show winner if the number is out of bounds (below 0 and above 9).

Hope this helps!

1 Like

The first thing I spotted was that the alert was coming up as soon as the page loads - because of window.alert(...)

If you replace that with Alert(...) The alert will only pop up after the condition is met and not on load.

I ran the code a few times - the Human did win at times first, but there were times the Computer won first.

Hope this helps!

Your compareGuesses function made a lot more sense to me than what was used. Thank you for sharing!

Thanks !
that helps a lot. On the side note, at my stage is it normal to be still very unsure with the syntax of Java script ? What is the level of competency expected?

regards,

Koo

1 Like

Yes it’s very normal. In a lot of fields you expect to pick things up fast but in programming in general it takes practice to get more comfortable and for the information to “stick”. I have found doing practice projects or code challenges to be really helpful.

After a while you realize you know that everything is relatively do-able but you have to keep looking things up all the time!