I am creating a Rock, Paper & Scissor game guided by odin project and the round() function is not able to return the value and pass it to the play() function from where it was called from and instead shows undefined even though both the getComputerChoice() and getPlayerChoice() functions are working fine as expected.
I was expecting the return of round() fn value to pass to play() fn and get the alert message which doesn’t show up. I don’t understand why.
// rock paper scissor game in console
// man vs computer game
// computer randomizer
// man input prompt
// game rounds
// result !
// ComputerChoice
function getComputerChoice() {
let value = Math.floor(Math.random() * 3);
if (value === 0) {
alert('I choose Rock');
return "Rock";
} else if (value === 1) {
alert('I choose Paper');
return "Paper";
} else {
alert('I choose Scissor');
return "Scissor";
}
}
// Use string method charAt and slice to make the
// case sensivity hide and always first letter capital
// after break
// PlayerChoice
function getPlayerChoice() {
let rawinput = prompt("Write your weapon : Rock, Paper or Scissor.");
let input = rawinput.charAt(0).toUpperCase() + rawinput.slice(1).toLowerCase();
if (input === "Rock") {
alert("Player chooses Rock");
} else if (input === "Paper") {
alert("Player chooses Paper");
} else if (input === "Scissor") {
alert("Player chooses Scissor");
}
return input;
}
// Single round of game
// -1 = lose 0 = tie 1 = win
// Values with respect to player
function round() {
getPlayerChoice();
// Stop unless input given
getComputerChoice();
if (getComputerChoice === "Rock") {
if (getPlayerChoice === "Rock") {
return 0;
} else if (getPlayerChoice === "Paper") {
return 1;
} else if (getPlayerChoice === "Scissor") {
return -1;
}
} else if (getComputerChoice === "Paper") {
if (getPlayerChoice === "Rock") {
return -1;
} else if (getPlayerChoice === "Paper") {
return 0;
} else if (getPlayerChoice === "Scissor") {
return 1;
}
} else if (getComputerChoice === "Scissor") {
if (getPlayerChoice === "Rock") {
return 1;
} else if (getPlayerChoice === "Paper") {
return -1;
} else if (getPlayerChoice === "Scissor") {
return 0;
}
}
}
// game starts here
function play() {
round();
if (round() == 0 ) {
alert('lose');
return "sadly noone wins";
} else if (round() == 1) {
alert('win');
return "winner winner chicken dinner";
} else if (round() == -1) {
alert('tie');
return "computer is smater than you because you lose";
}
}
play();
console.log(round());
2
Answers
Why call round every time?
And read some documentation about scopes in javascript: https://www.w3schools.com/js/js_scope.asp
Happy coding!