skip to Main Content

I am trying to solve a rock paper scissors game on freeCodeCamp. Here is the question:

In the game, there will be multiple rounds. The first to reach three points wins the game.

In this step, you will focus on determining if the player has won the round.

Complete the hasPlayerWonTheRound function. This function has two parameters: player and computer. The function should return true if the player has won the round, and false if the player has lost or tied the round.

Here are the criteria for the player to win a round:

If the player chooses "Rock" and the computer chooses "Scissors"
If the player chooses "Scissors" and the computer chooses "Paper"
If the player chooses "Paper" and the computer chooses "Rock"
A few function calls have been provided for you to test your function.

Here is what I have tried

function hasPlayerWonTheRound(player, computer) {
 if (player === "Rock" && computer === "Scissors") {
  return true;
  }

else if (player =="Scissors" && computer =="Paper") { 
  return true;
  }

else if (player =="Paper" && computer =="Rock") { 
 return true; 
 }

else if (player=="Rock" && computer=="Rock") {
  return false;
}

else if (player=="Paper" && computer=="Paper") {
  return false;
}
else (player=="Scissors" && computer=="Scissors") {
  return false;
}

When I submit this answer it says "Your hasPlayerWonTheRound function should return a boolean."

2

Answers


  1. First of all, your last else statement is wrong, it should be else if since you have a condition there.

    Second, your code doesn’t cover all possible cases, for example, when player == "Rock" && computer == "Paper", which means, that in this case your function will return undefined, which is not a boolean (which your error states). So, in order to solve it, you should either cover all remaining cases, or just have a return false statement at the end of your code, after the if, else if statements. This will ensure to return false in the rest of the cases. Hope, this clarifies it.

    And here’s a shorter solution, if you are interested. It will return true if any of those 3 conditions are true and false otherwise.

    function hasPlayerWonTheRound(player, computer) {
      return (
        (player === "Rock" && computer === "Scissors") ||
        (player === "Scissors" && computer === "Paper") ||
        (player === "Paper" && computer === "Rock")
      );
    }
    Login or Signup to reply.
  2. Try this

    function hasPlayerWonTheRound(player, computer) {
    
     if (player == "Rock" && computer == "Scissors" ||
         player =="Scissors" && computer =="Paper" ||
         player =="Paper" && computer =="Rock") return true
     else return false;
    
     }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search