Hi I am a newbie in JavaScript.I was trying to build a basic JavaScript rock paper scissor game..
I have implemented the below code.
The error I am getting is that while returning the value and displaying the return statement in the HTML I am always getting "The result is a tie",even though the computer and the user choices are different. I don't know where I have gone wrong.
Please help me out.The below is the code I have tried
<html>
<head>
<title>Input tutorial</title>
<script language="javascript">
var userChoice = prompt("Do you choose rock, paper or scissors?");
console.log(userChoice)
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67 && computerChoice > 0.34) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
alert("Computer: " + computerChoice);
var compare = function(userChoice, computerChoice) {
if (userChoice === computerChoice)
{
console.log("Here I amk")
return "The result is a tie!";
}
else if (userChoice === "rock"){
if(computerChoice === "scissors") {
return "rock wins";
}
else {
return "paper wins";
}
}
else if (userChoice === "paper"){
if(computerChoice === "rock") {
return "paper wins";
}
else {
return "scissors wins";
}
}
else if (userChoice === "scissors"){
if(computerChoice === "paper") {
return "scissors wins";
}
else {
return "rock wins";
}
}
else {
console.log(error)
}
};
//document.write(compare());
</script>
</head>
<body>
<h1>
Rock Paper Scissor Game
</h1>
<h1>
The result is <script>document.write(compare());</script>
</h1>
</body>
</html>
document.writeis useful if you want to support netscape navigator 1.0 or IE1 or mosaic - just don't do it - I don't want to discourage you from a path in javascript coding, but you need to look at more modern tutorials if you are serious about it