 # Number Guesser Challenge Project (JavaScript)

Make use of switch and cases. It is much more concise and easier to handle.

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

//Generate new secret target
const generateTarget = () => Math.floor(Math.random()*10);

const checkHumanGuess = (guess) => {
if(guess < 0 || theGuess > 9){
}
};

//
const getAbsoluteDistance = (guess, target) => Math.abs(target - guess);

//Determine who wins according to whose guess is the closest to the target number
//Returns true if human wins or if there's a tie, flase if computer wins
function compareGuesses (humanGuess, computerGuess, secretTarget){
return getAbsoluteDistance(humanGuess, secretTarget) <= getAbsoluteDistance(computerGuess, secretTarget);
}

//Increase the winner's score after each round
if (winner === 'human' ){
humanScore++;
} else if ( winner === 'computer' ){
computerScore++;
}
}

//Update the round number after each round.
const advanceRound = () => currentRoundNumber++;

``````

Hi, this is my code and everything works fine, however I do not have any idea how to implement the alert() function, are we supposed to call it from game.js? Or is it calling it from script.js?

Thank you

im still pretty new here myself, but i believe its not a function we call thats built into those two i think its a default function like how math() is a default function – i was able to implement it using below and it seemed to work pretty fine (obvi replace the parameter with yours)

if(humanGuess < 0 || humanGuess > 9){

}

additional : i slapped it inside the function that compares guesses – so that it checked what it received as a parameter from the compareGuesses() function first parameter spot – since that seems to be the only spot that the other JS hits us with the humans number when its pushed in the webpage, below is my full snippit and it works well, its not nearly as condensed as yours but ill get there eventually

``````
function compareGuesses(humanGuess, computerGuess, secretNum){
let winner, test1, test2;

if(humanGuess < 0 || humanGuess > 9){
}

test1 = getAbsoluteDistance(humanGuess, secretNum);
test2 = getAbsoluteDistance(computerGuess, secretNum);

if (test1 < test2){
winner='human';
}
if (test1 > test2){
winner='computer';
}
if (test1 === test2){
winner= 'human';
}

switch (winner){
case 'human' :
return true;
break;
case 'computer' :
return false;
break;
default :
return 'something went wrong';
break;
}
return winner;
}
``````

@imagodei
the absolute method would be a method that takes the difference between the computer / human guesses and does the math.abs() portion for you, then returns the value for use inside the compareGuesses() function

it looks like you might have missed the math.abs portion?

@malamid13, yes. I did not use the absolute method because i did not understand how to use it. Thank you for explaining.

Hi I’m new here and new to JS functions. I’ve created the project but, somehow my game can’t perform more than 4 rounds… Can you please take a look at my code and see what went wrong? Thanks a lot

``````function generateTarget() {
return Math.floor(Math.random() * 10);
};

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

if (winner === 'human') {
humanScore++;
}
else if (winner === 'computer') {
computerScore++;
}
else {
console.log('Error!');
}
};

currentRoundNumber++;
};
``````

Took me a few minutes to find someone else who created variables within the compareGuesses function. Glad I’m not the only one who did that!

I read through most of the posts to see if there was anyone else who realized a problem in both the solution folder and the codecademy project. Someone would have to look in the game.js file to see the problem, but it is not big enough to prevent coders from accomplishing the project.

This post was the only one I saw address the problem. Unfortunately, he did not expound on why this issue occurs. There are also other issues outside of the input box that somewhat break the game after you get it working.

Inside of the game.js file there are event listener functions that determine what to do when you click the ‘Make a guess’ and ‘Next Round’ buttons. There is also an extremely crucial `handleValueChange` function:

``````const handleValueChange = value => {

if (value > 0 && value <= 9) {

subtractButton.removeAttribute('disabled');

} else if (value > 9) {

} else if (value <= 0) {

subtractButton.setAttribute('disabled', true);

}

}
``````

It checks the input box’s value and makes the +/- buttons work. The initial condition set for the `handleValueChange` function allows the add button to go up to 10. You can also freely set any number by typing in the box, so you can always guess higher than the input range. If you change the first `if` statement in the function to `if (value > 0 && value < 9) {. . .}` then it will restrict the +/- buttons to between 0 and 9. However, this was likely left for adding that alert function solution.

The number box can have its value input feature removed, only leaving the +/- buttons working, which is maybe the best solution, as the codepen by dyrits does; or you can disable the guess button for values greater than 9 or less than 0: greater than 10 in my case.

The reason why I would say disabling the input box is a better solution is because the value can be changed between rounds by the input box and +/- buttons, which can disrupt the conditions set in `handleValueChange`. This is because the solution and initial project code do not call `handleValueChange` after pressing the guess and next round buttons. I believe someone had asked why the value can go to -1 after pressing the next round button and that is why.

I think the project should be adjusted to ask users to do some simple debugging on the game.js file because that taught me significantly more than just trying to do the project. Have us look into `document.getElementById()` and explore the functions used to build the game.

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

// Generate Target Function

function generateTarget() {
return Math.round(Math.random() * 10);
}

// Compare Guesses Function

function compareGuesses(HUMg, COMg, tar) {
let closestGuess;
let humanGuess = (h,t) => Math.abs(t-h);

let computerGuess = (c,t) => Math.abs(t-c);

closestGuess = ( (humanGuess(HUMg, tar) < computerGuess(COMg, tar)) || (humanGuess(HUMg, tar) == computerGuess(COMg, tar)) ) ?
'human' : 'computer';

console.log(closestGuess);
return closestGuess;
}

// Update Score Function

if (victor == 'human'){
humanScore++;
} else {computerScore++;}
}

currentRoundNumber++;
}
``````
1 Like

Change the greater-than and less-than symbols on your if statements in the `compareGuesses` function.

``````function compareGuesses(humanGuess, computerGuess, targetNumber) {
if (Math.abs(targetNumber - humanGuess) < Math.abs(targetNumber - computerGuess)) {
return false;
}
else if (Math.abs(targetNumber - humanGuess) > Math.abs(targetNumber - computerGuess)) {
return true;
}
else {
return true; //This is fine
}
}
``````

You can also just change the `true` and `false` positions in the `if` and `else if` statements

Boolean is binary. When is there ever a third outcome?

``return Math.abs(targetNumber - humanGuess) < Math.abs(targetNumber - computerGuess)``

Thank you 1 Like

Sorry, but this does not address the condition of when they are both equal to each other.

```````return Math.abs(targetNumber - humanGuess) < Math.abs(targetNumber - computerGuess)`
``````

Although that would be the most concise way to check true and false statements.

Granted, but that check can be done in advance.

I actually began to argue that the representation of boolean logic was inaccurate because it assumed that all checks would be confined to just the two conditions. In truth, boolean logic can be extremely versatile and apply several logic checks relative to the degree that a condition’s outcomes are addressed.

The initial project code had somewhat faulty logic because it assumed that the only conditions for determining input value of the number box would be confined to the +/- buttons, and did not consider the loss of those checks when the ‘Next Round’ button was enabled, or after the guess button was pressed. That allowed you to freely press the +/- buttons to produce any value, negative or positive.

I would agree there. So another solution would be

``````function compareGuesses(humanGuess, computerGuess, targetNumber){
let targetDifference1 = Math.abs(humanGuess - targetNumber);
let targetDifference2 = Math.abs(computerGuess - targetNumber);
let closestGuess = ( targetDifference1 > targetDifference2 );

return (targetDifference1 == targetDifference2) ? true : closestGuess;
}
``````

Hi, i was working on this project. But i am facing the issue that my target number code doesnt work. It shows undefined although i have tried my best to not make an error. Would you please help me out?.
this is my code:
let humanScore = 0;
let computerScore = 0;
let currentRoundNumber = 1;

function generateTarget()
{var targetNumber=Math.floor(Math.random * 10);};
function compareGuesses(userGuess,computerGuess,targetNumber){if(Math.abs(targetNumber-userGuess)>Math.abs(targetNumber-computerGuess))
{return false;}
else if(Math.abs(targetnumber-computerGuess)>Math.abs(targetNumber-userGuess))
{return true;}
else {return true;}};
{if(winner===‘human’){humanScore++;}
else{computerScore++};};
{currentRoundNumber++;};

THE TARGET NUMBER ON THE BROWSER DOESNT CHANGE.
it just says undefined. no matter what i do.
Thanks.

Hey all,

can anyone help me understand where my code is going wrong? I can’t seem to have the guessing give me anything.

The function is not returning anything. Plus the `random` method is missing `()`.

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

Hello guys! Here’s my project

I’ve tried doing the extension task of adding an alert() function (lines 11-15) but for the life of me I can’t make it work. Any advice?

Where is the human guess?

You do know about the built in `alert()` function of JS, right? We do not have to write it.

When a user’s input is out of range we have two choices…

• Terminate the program and let the user Run it again; or,
• loop back to the input statement and try again.

Pick one, then plan out how you will make either work, then implement the plan.

1 Like