Number Guesser for Javascript

Hey folks!! I have just started and I’m struggling with the Number Guesser project as I still lack basic understanding of how functions work. It’s the first “unassisted” project I take. This is the link:

I’m stuck at task 5:

Create an updateScore() function. This function will be used to correctly increase the winner’s score after each round.

First of all: Why do I need to create a function to change the scoreboard in the first place? Couldn’t I just write code to change it after I set the winner in the “compareGuesses” function?

This function:

  • Has a single parameter. This parameter will be a string value representing the winner. I couldn’t figure out what to do here.
  • Increases the score variable ( humanScore or computerScore ) by 1 depending on the winner passed in to updateScore . The string passed in will be either 'human' or 'computer' .**Also have no idea what to do her. I don’t remember learning any thing that alters a variable somewhere else, during the course so far. I’d love to be pointed out to what type of code I should write so I can research? From what I understand it would something like "if winner is such, then score=score+1 **
  • Does not need to return any value.

Sorry about the beginners question!:laughing:

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

// Write your code below:

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

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; 
}
  
}
              

const updateScore = (winner) => {
 
}

1 Like

yes, but putting everything in a single function you get spaghetti code, an unmaintainable and untestable bunch of gibberish. The function names also help to identify which part of the program has which job.

you seem to have figured this out:

const updateScore = (winner) => {
 
}

i see a function with a parameter

now based of who won you can call the function:

const updateScore = (winner) => {
 
}

updateScore('human') # represents the user winning
updateScore('computer') # represents the computer winning

then within the function, we need a comparison (so if and else) to determine who won.

after you defined a variable:

let humanScore = 0;

you can change the value:

humanScore = 5;

or you could increase the score:

humanScore = humanScore + 1

surely this has been taught?

1 Like

Im stuck, Im not understanding the function that is needed to be in the updateScore, can someone show me the code so i can make sense of it?

I don’t give away code solutions, i help people.

Here is my code:

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

// Write your code below:

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

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(humanScore){
  console.log(humanScore + 1);
}
else if(computerScore){
  console.log(computerScore + 1);
}
else{
  console.log('error');
}

I am printing an error and I think it is because I am not printing a target number, help!

For future reference, please click on the </> icon before pasting your code, and then paste it in the space specified. This will preserve your original formatting, and make your code easier to read.
You have some unnecessary parenthesis here, and an unnecessary else statement. See my comments:

In this project we aren’t using the console for any results. The results are being displayed on the web page in the browser pane. Instead of logging anything to the console, you need to update (increase by 1) the variable that points to the value for either the human or the computer. Also keep in mind that the variable winner is either true or false. If the human player won it’s true, otherwise it’s false. Your if conditions inside your updateScore function need to determine who won. See what you can do, and repost your code if you need more help. Good Luck!

the body of your function is empty:

const updateScore = (winner) => {
  // empty body of function
  } // closes function

furthermore, you do nothing with the winner parameter of the function

here is my code, I can’t work out why it won’t properly calculate the winner. It doesn’t give any errors, but when the numbers are compared it doesn’t declare the proper winner, for example if the target is 8, the computer guess is 8, and the human guess is 3, it will declare the human the winner.

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

function generateTarget() { // generates a random numbers between 0 and 9
    return Math.floor(Math.random() * 10);
}

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;
}

function updateScore(winner) { // updates the score of the winner, either computer or human.
    if (winner === 'human') {
        humanScore++;
    } else if (winner === 'computer') {
        computerScore++;
    }
}

function advanceRound() {
    currentRoundNumber += 1
}

// console.log(generateTarget())
// console.log(compareGuesses(8, 4, 8))

Nevermind, I figured out that in the compareGuesses function I had put the computerGuess and humanGuess parameters the wrong way round.

Here is my take on this exercise. The game works, in that I can guess a number, and there’s a target number and computer guess. But I can’t figure out why the round number won’t advance, or why the score isn’t updated.

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

// Write your code below:
function generateTarget() {
  return Math.floor(Math.random()*10)
}
const compareGuesses = (humanGuess, computerGuess, targetNumber) => {
  if ((Math.abs(humanGuess - targetNumber)) < (Math.abs(computerGuess - targetNumber))) {
    return true; 
  } else if ((Math.abs(humanGuess - targetNumber)) > (Math.abs(computerGuess - targetNumber))) {
    return false;
  }
}
const updateScore = () => {
  if (compareGuesses = true) {
    let humanScore = humanScore + 1
  } else if (compareGuesses = false) {
    let computerScore = computerScore + 1
  }
}
const advanceRound = () => {
  if (compareGuesses = true) {
    let currentRoundNumber = currentRoundNumber + 1
  } else if (compareGuesses = false) {
    let currentRoundNumber = currentRoundNumber + 1
  }
}

I thought by using the compareGuesses It would check that someone won, and based on who record the score. I just don’t understand why it doesn’t work like this.

There are no function calls at all? So nothing is happening?

also here:

if (compareGuesses = true) {
    let currentRoundNumber = currentRoundNumber + 1
  } else if (compareGuesses = false) {
    let currentRoundNumber = currentRoundNumber + 1
  }

both if and else if block do the same. So you don’t need the conditions? (which are also faulty, you do an assignment in if condition.

Ok. So I went back and rewrote it to this (with help from this thread above):

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

Now everything except the computerScore works, which remains 0 no matter what. The game correctly announces the computer as winner though, it just won’t give it any points.

Also, I hope what you referred to above was the fact that I used let in front of the functions, instead of calling them?

I would also like to say that I very much appreciate your help, and patience, with my (probably) very silly questions.

You simply didn’t post the function calls in the topic?

A function consist of two parts, a function declaration/definition and a call, the latter will actually execute the function. Using const is good

this:

winner = 'human'

is an assignment, not a equality comparison. As you currently wrote it, its always true. The string is assigned, then the string evaluated as truthy

Ahh, ok. So that’s the difference between using “=” and “===”. Thank you for clarifying :slight_smile:

My script.js file will allow me to play the game in the codeacademy console (it still won’t update the currentRoundNumber), but when I try and play it in Chrome nothing happens when I click ‘Make a Guess’. I extracted all the files from the zip and put them in the same folder, copied the index.html path and I get the home page I would expect. Nothing seems to be interactive though.
Is there something I need to do to link up my files?

HTML needs to know the load the JS, did you include <script>?

a webpage and a console are two different things. Console is part of the dev tools. Try pressing f12 and then navigate to the console tab

@stetim94 I am trying to understand step #5 as well (as described above) and have read your response to @pabloaguirre21066569.

The strings are called after the function’s if else statement, so can I assume that the if else statement must contain those same strings like so:

const updateScore = (winner) => {
  if (winner === 'human') {
    humanScore++;
  } else if (winner === 'computer') {
    computerScore++;
  } else {
#not sure what the else would be...
};

and then then this comes after?

updateScore('human')
updateScore('computer')

what do you mean by this? Functions gets executed when called. You can’t call something you haven’t defined.

you don’t need an else. Although you could use else to throw an exception

I’m stuck at task 5:
Not sure why the score isn’t updating

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

// Write your code below:

// Target Number function
const generateTarget=()=>
  Math.floor(Math.random() * 10);

//Determines the Winner
const compareGuesses=(humanGuess,computerGuess,targetNumber)=>{
  let humanDiff = Math.abs( targetNumber- humanGuess );
  let computerDiff = Math.abs( targetNumber- computerGuess);
  if (humanDiff< computerDiff){
    return true;
  } else if (humanDiff>computerDiff){
    return false;
  } else if (humanDiff===computerDiff){
    return true;
  }
}


//updates the score and winner
const updateScore=()=>{
  if (compareGuesses===true){
    humanScore++;   
  } else if (compareGuesses===false){
    computerScore++; 
  }
}



   





I don’t see any function calls? Without a call, a function won’t be invoked.