Number Guesser for Javascript

I afraid I’m on the step before the beginning of the post, but didn’t want to start a new thread.

I noticed that everyone is using

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

I can’t figure out why this

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

doesn’t do the same thing?

a new thread is preferable, otherwise topics/threads become a clutter.

because in the first example, you use an implicit return. This shorthand is only allowed for es6 arrow functions.

Thanks… I did find that as I looked online, but decided to use the arrow function… So now that I’ve caught up with everyone else on this, I did the following for the Math.abs - the numbers seem to generate fine, but for some reason it’s not printing out the “return”

let humanScore = 0;

let computerScore = 0;

let currentRoundNumber = 1;

// Write your code below:

const generateTarget= () => {

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

return Math.floor(Math.random() * 9);

};

generateTarget();

let targetNumber = generateTarget();

let humanTarget = Math.abs(humanScore - targetNumber);

let computerTarget = Math.abs(computerScore - targetNumber)

function compareGuesses(humanTarget, computerTarget, targetNumber){

  if(humanTarget < computerTarget){

    return true

  }else if(humanTarget >  computerTarget){

    return false

  }else{

      return true

    }

  }

TIA

now you generate a random number twice:

const generateTarget= () => {

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

return Math.floor(Math.random() * 9);

};

the first random generated number is just discarded.

printed where? To the console or the the web page?

The thing I struggle with is how the script knows what number “target” is?

target is a function parameter. Given functions aren’t executed until they are called, parameters act as placeholder

when you call the function, you can provide arguments for your parameters.

1 Like

But nowhere in the code is a value given for target?

you don’t have a variable named target. What variable are we talking about? I thought you meant one of the parameters on this line:

function compareGuesses(humanTarget, computerTarget, targetNumber){

like I said in my answer, the values for parameters come from arguments at function call. You never call the compareGuesses. Would be a good challenge to do so :slight_smile:

Sorry about the confusion!

function compareGuesses(computerGuess, humanGuess, target) { // compares the guesses, returns true if human wins.
    const humanDifference = Math.abs(target - humanGuess);
    const computerDifference = Math.abs(target - computerGuess);
    return humanDifference <= computerDifference;

I was talking about the variable “target” in this piece of code. Where does “target” get it’s value from?

Given my explanation was generic on parameters, what I explained still applied. Parameters get there values from arguments. For example:

function greet(name){
    return `greeting ${name}`
}

console.log(greet('thomas'))

the name parameter gets its value ('thomas' string) from the argument at function call. Which means if we want to greet another person we can easily do:

console.log(greet('stetim'))

so the same applies to your function, which is why I suggested you should add function calls for practice :slight_smile:

I understand that.
However: if this function gets theinput for computerGuess from the webpage, the humanGuess from the input on the webpage, how does it get the “target” variable? it is not defined anywhere in the code.

This exercise contains extra code, which we can inspect:

let target;

const humanGuessInput = document.getElementById('human-guess');

const roundNumberDisplay = document.getElementById('round-number');

const computerGuessDisplay = document.getElementById('computer-guess');
const humanScoreDisplay = document.getElementById('human-score');
const computerScoreDisplay = document.getElementById('computer-score');
const targetNumberDisplay = document.getElementById('target-number');
const computerWinsDisplay = document.getElementById('computer-wins');

const guessButton = document.getElementById('guess');
const nextRoundButton = document.getElementById('next-round')

guessButton.addEventListener('click', () => {
  // Generate the target value
  target = generateTarget();
  // Retrieve the player's guess
  const currentHumanGuess = humanGuessInput.value;
  // Make a random 'computer guess'
  const computerGuess = Math.floor(Math.random() * 10);

  // Display the computer guess and the target
  computerGuessDisplay.innerText = computerGuess;
  targetNumberDisplay.innerText = target;
  
  // 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!!!';
  }

  // winnerDisplay.innerText = humanIsWinner ? 'You win!' : 'Computer wins!';

  // Display the current scores:
  humanScoreDisplay.innerText = humanScore;
  computerScoreDisplay.innerText = computerScore;
  
  // Set the correct disabled state for the buttons
  guessButton.setAttribute('disabled', true)
  nextRoundButton.removeAttribute('disabled');
});

nextRoundButton.addEventListener('click', () => {
  // Increase the round number
  advanceRound();
  // Display the new round number
  roundNumberDisplay.innerText = currentRoundNumber;

  // Set the correct disabled state for the buttons
  nextRoundButton.setAttribute('disabled', true);
  guessButton.removeAttribute('disabled');

  // Reset the guess input box and the target number display:
  targetNumberDisplay.innerText = '?';
  guessButton.innerText = 'Make a Guess';
  humanGuessInput.value = '';
  computerGuessDisplay.innerText = '?';
  computerWinsDisplay.innerText = '';
  guessButton.classList.remove('winning-text');
});

const addButton = document.getElementById('add');
const subtractButton = document.getElementById('subtract');

addButton.addEventListener('click', () => {
  humanGuessInput.value = +humanGuessInput.value + 1;
  handleValueChange(humanGuessInput.value);
});

subtractButton.addEventListener('click', () => {
  humanGuessInput.value = +humanGuessInput.value - 1;
  handleValueChange(humanGuessInput.value);
});

const handleValueChange = value => {
  if (value > 0 && value <= 9) {
    subtractButton.removeAttribute('disabled');
    addButton.removeAttribute('disabled');
  } else if (value > 9) {
    addButton.setAttribute('disabled', true);
  } else if (value <= 0) {
    subtractButton.setAttribute('disabled', true);
  }
}

humanGuessInput.addEventListener('input', function(e) {
  handleValueChange(e.target.value);
});

when you click the button, the generateTarget function is called:

target = generateTarget();

which is then used to when the function is called:

const humanIsWinner = compareGuesses(currentHumanGuess, computerGuess, target)

the exericse does some lifting here so you don’t have to deal with interacting with the webpage.

I came on here because I was stuck with the Maths.abs bit, this helped - thank you

But there are some mistakes in this code. The original poster as probably solved this now, but it might help others:

0-9 wants to be generated, so the multiply needs to be 10

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

the < beside Math.abs needs a space, same with the one near the bracket.

if (Math.abs (humanGuess-targetGuess() )< Math.abs( computerGuess-targetGuess() )){ return true;                                                                        
} else if  (Math.abs (humanGuess-targetGuess() ) > Math.abs( computerGuess-targetGuess() )){
  return false; 
}
 } 

I’m on the updateScore section now

edit

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

no else is needed. Also, going back to my corrections on the other person’s code, Math.abs can be defined as a variable within the compareGuesses function

const compareGuesses = (para1, para2, para3) => {
  const humanDifference = Math.abs (para3-para1)
  const computerDifference = Math.abs (para3-para2)
}

note para is short for parameter

Hey everyone! I’m stuck right now inStep 5. Right now, I think I got the function right, but the console says that humanScore variable and computerScore are not defined. I really do not know what dumb thing I’m doing because even when I reassign the variables inside the function, it still gives the same error. I hope I was clear, and thank you to whoever helps!

Here’s my code:

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

// Randomizer

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

// The Game

let compareGuesses = (humanGuess, computerGuess, targetNumber) => {

    let humanPoint = Math.abs(humanGuess - targetNumber);
    let computerPoint = Math.abs(computerGuess - targetNumber);

    if (humanPoint <= computerPoint) {
      return true; 
    } else {
      return false;
    }
  }

//Score Updater

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

  console.log(updateScore('human'));

what makes you think that? Because you see undefined in your output window/console?

the variables are defined, but you attempt to log the return value of a function here:

  console.log(updateScore('human'));

but this function does not return anything, as a result, you get undefined

if you attempt to log humanScore:

console.log(humanScore)

everything goes fine

Yes! That’s exactly what happens. But I don´t get why console.log(humanScore) would fix this whole thing. Although I understood what you meant by the function not returning anything.

//Score Updater

const updateScore = (win) => {


    if (win === 'human') {
      humanScore += 1;
      console.log(humanScore);
    } else if (win === 'computer') {
      computerScore += 1;
      console.log(computerScore);
    }
  }

console.log(humanScore);

Thank You for your time!

there wasn’t much wrong with your code, you where just not logging the right thing

1 Like

Hi everyone! I’m stuck at step 5, the score won’t update… Can someone explain me why?
here is the code:

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

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

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

Hello, @marcuadrian367658120, and welcome to the forums.

If you open your browser’s console, you may see an error message when you try to play the game.

Hint:

Hello i am a new user and i was wondering if someone could help with this problem. Im getting an unexpected token issue with the if statements.

const compareGuesses = (userGuess, Usercomputer, targetNumber) => {
  if (Math.abs(userGuess - targetNumber() ) < Math.abs(computerGuess - targetNumber() ) {
    return true
  } else if (Math.abs(userGuess - targetNumber() ) > Math.abs(computerGuess - targetNumber() ) {
    return false;
  }
}

  if (Math.abs(userGuess - targetNumber() ) < Math.abs(computerGuess - targetNumber() ) {
                                                                                        ^
SyntaxError: Unexpected token {