user3638147
user3638147

Reputation: 45

Javascript Rock, paper, scissors game. Whats wrong with my code?

I want the code to grab the value that the user has entered in the input field and pass it to a variable userChoice. I have no idea why this code isn't working and the only way to learn is to ask you guys.

HTML:

<h3> Choose your destiny !</h3>

<form>
    <input type="text" id="form" />
    <input type="button" id="button" value="Click Me!" onclick="clickMe();" />
</form>

JavaScript:

var computerChoice = Math.random();
var userChoice = "";

function clickMe() {
    document.getElementById("form").value === userChoice;
}

if (computerChoice < 0.33) {
    computerChoice = "rock";
};
if (computerChoice < 0.66) {
    computerChoice = "paper";
};
if (computerChoice < 1) {
    computerChoice = "scissors";
};

if (userChoice === "rock" && computerChoice === "rock") {
    alert("It's a tie!");
} else if (userChoice === "rock" && computerChoice === "paper") {
    alert("Computer Wins!");
} else if (userChoice === "rock" && computerChoice === "scissors") {
    alert("You WIN!");
};

if (userChoice === "paper" && computerChoice === "rock") {
    alert("You WIN!");
} else if (userChoice === "paper" && computerChoice === "paper") {
    alert("It's a TIE!");
} else if (userChoice === "paper" && computerChoice === "scissors") {
    alert("Computer Wins!");
};

if (userChoice === "scissors" && computerChoice === "rock") {
    alert("Computer Wins!");
} else if (userChoice === "scissors" && computerChoice === "paper") {
    alert("You WIN!");
} else if (userChoice === "scissors" && computerChoice === "scissors") {
    alert("It's a TIE!");
};

Fiddle

Upvotes: 0

Views: 448

Answers (2)

G&#252;ven Altuntaş
G&#252;ven Altuntaş

Reputation: 253

Here is the simple way

<div id="Result"></div>
<div id="sellection">
    <a href="javascript:;" onClick="result(0)">Rock</a>
    <a href="javascript:;" onClick="result(1)">Paper</a>
    <a href="javascript:;" onClick="result(2)">Scissors</a>
</div>

and the script is:

function result(users){
    var choices = ["Rock","Paper","Scissors"];
    var succesResult = "You Loose :(";
    var machines = Math.floor((Math.random() * 3)); 
    var dif = users-machines;
    if(dif>0&&dif!=2||dif==-2){
        succesResult = "You Win :)";
    }else if(dif==0){
        succesResult = "You Draw";
    }
    var resultText = "You Selected "+choices[users]+", Computer Selected "+choices[machines]+" and "+succesResult;
    document.getElementById("Result").innerHTML = resultText;
}

Upvotes: 0

Jonathan
Jonathan

Reputation: 9151

Your function clickMe doesn't work like you'd expect I guess:

function clickMe() {
     userChoice = document.getElementById("form").value;

    // ... rest of your code goes inside clickMe
}

To assign a value to a variable you need a single =

Upvotes: 2

Related Questions