Number Guesser Challenge Project (JavaScript)

Hi,
here is my first JS file.
I am looking forward to getting your feedback, and your rate.

Thanks in advance

link => https://gist.github.com/Raminkeshavarzi/c89618e8962992c93d9d2e837421a19a

link =>https://gist.github.com/682eadb94ca450e4ca972e166b4158df

Hello!

here is my project!

thanks,

return differenceUser <= differenceComputer;

I really couldn’t wrap my head around that statement, because I didn’t comprehend how it related to the output of the result on the website. I was thinking “ok, it evaluates to true, now what? How does the program know that because it’s true, the human wins, since I haven’t coded that anywhere?”.

Then I took a look at the game.js file to see if I could find some answers there, and I did:

 // 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!!!';
  }

So we have the compareGuesses function, which is expected to return a Boolean value. The result (true or false) is the value assigned to a new variable humanIsWinner. That variable will then be re-used in an if statement that will run a different code (who won) depending on if the value assigned to humanIsVariable is truthy or falsy.

I just think I needed to lay it out because given that the instructions mention that you don’t need to look at the game.js file, it took me some time to figure this one out in the solution code. So I’ve replaced the logic I had written in compareGuesses() with the solution code (mine was an if/else if statement that resulted in incorrect logic when playing the game).

Now though, I’m stuck with the extra challenge of making a separate getAbsoluteDistance() function. Here is my code below after much rewriting to test different things. Can someone hint me towards what I’m doing wrong? (Many things I suspect?)
(I also didn’t see a solution on this part of the project in the thread I think)

Many thanks!


My project is working fine. Please provide your feedback.

So this is my solution to this challenge.

I was struggling hard on this challenge trying to get the results displayed on the console instead of trying them out in the actual game. Wrong thing to do. I was trying very hard to get the console to display what I was expecting it to display without being aware that the challenge is asking for simple functions, and the logic on how this functions are applied to the game is on game.js which I completely forgot. This happened in step number 5 mostly.

However, after realizing I just had to focus on the functions and not the actual game logic I was able to complete everything relatively fast.

Great challenge to put things in perspective and realize that many times we try so hard to prove ourselves right by trying to test our code in many different ways and making it more complicated. Sometimes we should just sit back, look everything from a general perspective and ask ourselves, am I just complicating this more than I should?

Many times the answer could be yes. Remember: keep it short, keep it sweet, keep it simple.

I was wondering if someone could help me understand where I went wrong in step 4 of this challenge.

I see in the most recent comment "I was struggling hard on this challenge trying to get the results displayed on the console instead of trying them out in the actual game. " Which I think is likely what tripped me up.

Step 4 asks:

Create a compareGuesses() function. This function will be called each round to determine which guess is closest to the target number.

This function:

  • Has three parameters representing the user (human) guess, a computer guess, and the secret target number to be guessed.
  • Determines which player (human or computer) wins based on which guess is closest to the target. If both players are tied, the human user should win.
  • Return true if the human player wins, and false if the computer player wins.

This is the code I did:

const compareGuess = (human, computer, target) => {
    if (Math.abs(human) - target >= Math.abs(computer)- target) {
        return true;
    } else {
        return false;
    }
}

But when I downloaded the solution to compare it, the code is very different and doesn’t look to return either true or false.

Using Math.abs() on a number that you know is positive is pointless since its already positive. A better use would be to pass in an equation that you’re not sure if its going to be positive or negative. For example, Math.abs(3 - 9) and Math.abs(9 - 3) both equal 6 rather than the first one being -6 and the latter being 6.

The solution does return a true or false. It is just using a conditional in the return statement.

if(3 < 9)
  return true;
else
  return false;

These two do exactly the same just written differently

return 3 < 9;

Ah ok, I think I understand it better now, especially the return part which I was struggling to wrap my head around :slight_smile:

So my original code could be (hopefully) more correctly written like this?

const compareGuess = (human, computer, target) => {
    return (Math.abs(human - target) >= Math.abs(computer - target));
}

Which should return true if the human is greater than or equal to the computer right?

Thank you for your reply btw!

Good morning,

After a few minutes and hours of research I was able to reach this solution, I share it to see your opinions about it, I hope it is of your help.

Thank you and happy coding :smile:

Number Guesser

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

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

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

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

const advanceRound = () => currentRoundNumber++;

My first code :sweat_smile:

Hello,

Here is my solution to the challenge project :slight_smile:

I tried to complete the challenge with as simple, punchy and short code as possible. I was able to use ternary operators to reduce the code to just 5 lines in total.

My first post and first ‘challenge’ – thoughts appreciated!! Just a note looking at others’ work:

I’ve noticed that a lot of people have calculated the random number with:

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

I’m not sure that’s correct, as the function is supposed to return a random number between 0 and 9, and there’s a slim chance that Math.random() returns a ‘1’, in which case the function would return a ‘10’ as the generated number. I’ve used

Math.round(Math.random()*9),

Though statistically, I think it makes the probability of 0 and 9 occurring statistically less likely.

EDIT: I’ve just looked into Math.random() and it does return a number between 0 and 1, but not inclusive of 1, so Math.floor(10*Math.random()); is correct.

Hi!
I’m a little bit confused in the last section because the next round button still of. Do anybody can help me with this?
My Sourcecode

Hello everyone.
Here is mine :grinning:

Hi!
Here is my code.
It works fine, except for one issue:
when I type a number out of range and press ‘Make a guess’, the window alert shows up and the computer wins, but in the next round the ‘+’ (plus signal) won’t work anymore until I insert a number (inside range) by typing it.

Could anyone help me solve this please? Thanks a lot!

Went back to this project because 25 days ago I wasn’t able to finish the project extension with getAbsoluteDistance() which was really bothering me. I’m really proud now to have a full functioning code and with 4 functions out of 5 being one liners!

can someone please tell me why computer keeps winning

    let userD = getAbsoluteDistance(user - target)
    let compD = getAbsoluteDistance(computer-target)

Recall that your function is doing the subtracting so just pass the two values as separate arguments.

getAbsoluteDistance(user, target)
getAbsoluteDistance(computer, target)

yeah… that’s correct.
thanks a lot

1 Like

hello, i just don’t understand

return humanDifference <= computerDifference;
in the course ive never seen something like that.
i just used an if statement instead but id like to know how to use this shorter form.