Alex Wohlbruck Alex Wohlbruck - 26 days ago 6
Javascript Question

Programming a rock, paper, scissors game

I am making a little rock paper scissors game, and I thought I planned everything out perfectly, but for some reason nothing happens when you try to play.

Basically, there are three images, a rock, a piece of paper, and some scissors, and you click one. Using the code I typed, the computer generates a random value and that value is converted to either rock, paper, or scissors. When the player clicks on an image, it sets the players choice to rock, paper, or scissors as well. Then javascript runs some if else statements to compare the two choices, and decides the winner.

Code:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Rock Paper Scissors</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<style>
body {
font-family: Roboto, Arial;
}

.choose img {
width: 150px;
margin: 20px;
}
</style>
</head>

<body>

<div class="choose" align="center">
<h2 id="question">Rock, paper, or scissors?"</h2>
<img src="http://img2.wikia.nocookie.net/__cb20141120133208/epicrapbattlesofhistory/images/4/4b/A_Rock!.gif" id="rock"><img src="http://www.clipartpal.com/_thumbs/pd/education/paper_sheet.png" id="paper"><img src="http://www2.fiskars.com/var/fiskars_amer/storage/images/frontpage2/sewing-quilting/products/scissors-and-sharpeners/the-original-orange-handled-scissors-8/16933-6-eng-US/The-Original-Orange-Handled-Scissors-8_product_main.png" id="scissors">
</div>

<script>

var computerChoice = math.random();
var userChoice = null;

//Change randomly generated number to rock, paper, or scissors
if (computerChoice < .33) {
computerChoice == "rock";
} else if (computerChoice < .66) {
computerChoice == "paper";
} else {
computerChoice == "scissors";
};

//Set userChoice variable to rock, paper, or scissors
function convertUserChoice() {
$('#rock').click(function() {
userChoice == "rock";
});
$('#paper').click(function() {
userChoice == "paper";
});
$('#scissors').click(function() {
userChoice == "scissors";
});
};

//Compare computerChoice with userChoice, decide who wins
if (userChoice == computerChoice) {
alert ("Tie!");
} else if (userChoice == "rock") {
if (computerChoice == "scissors") {
alert ("You win!");
} else {
alert ("You lose.");
};
} else if (userChoice == "paper") {
if (computerChoice == "rock") {
alert ("You win!");
} else {
alert ("You lose.");
};
} else if (userChoice == "scissors") {
if (computerChoice == "paper") {
alert ("You win!");
} else {
alert ("You lose");
};
};

</script>
</body>
</html>


Here is a link to the actual html page:
https://747d6108ac1130fc3601936220515b351efca1a4.googledrive.com/host/0B4rWYiw5-JZtfjJpT2M0WUNRRGtWQ250RElDc2QxRUc2aEdzajFERWkzVUVTd0pkNlY3LXc/RPS.html

I think the problem is that the js code labeled "Compare computerChoice with userChoice, decide who wins" isn't running when the user clicks the image. If so, how could I make it do so?

Answer Source

There are some problems in your code:

  1. Your click handlers are not attached to the DOM elements because you haven't called convertUserChoice(). Just remove the function and it will be working.
  2. Use = instead of ==. Asignment is needed and not comparison.
  3. You need to create functions for computerChoice and checkChoise so you can call them when needed.
  4. Of course, as mentioned in the comments Math upercase is required.

Please find your code in this jsFiddle and below.


Update

You could improve your winning check by using a object for the check. The object stores each winning situation for the user. e.g. if the user chooses rock then winningCombinations['rock'] will return the value scissors and that's a winning situation if computerChoice is scissors the comparison will return true and the string win will be the result. (See updated code below.)

That's easier than your if/else conditions.

    var computerChoice = null,
        userChoice = null;

    var newComputerChoice = function () {
        computerChoice = Math.random();
        //Change randomly generated number to rock, paper, or scissors
        if (computerChoice < .33) {
            computerChoice = "rock";
        } else if (computerChoice < .66) {
            computerChoice = "paper";
        } else {
            computerChoice = "scissors";
        };
        console.log('pc choice: ', computerChoice);
    };

    //Set userChoice variable to rock, paper, or scissors
    //function convertUserChoice() {
    $('.choose>img').click(function () {
        var id = $(this).attr('id');
        userChoice = id.substring(0, id.length); //#rock --> remove #
        console.log('user choice: ', userChoice);
        newComputerChoice();
        checkChoice();
    });

    var checkChoice = function () {
        var message = function(msgType) {
            var msgTypes = ['win', 'lose'],
                index = msgTypes.indexOf(msgType),
                format = ( index != -1 ) ? 'You %1$s!': 'Tie!';
            
            alert(sprintf(format, msgTypes[index]));
        };

        var winningCombinations = {
            // userchoice: computerchoice
            rock: 'scissors', // you win
            paper: 'rock',    // you win
            scissors: 'paper' // you win
        };
        
        var result;
        
        //Compare computerChoice with userChoice, decide who wins
        if (userChoice == computerChoice) {
            message('tie');
        }
        else {
            result = ( winningCombinations[userChoice] == computerChoice ) ? 'win': 'lose';
            message(result);
        }
    };
body {
    font-family: Roboto, Arial;
}
.choose img {
    width: 150px;
    margin: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="choose" align="center">
     <h2 id="question">Rock, paper, or scissors?"</h2>

    <img src="http://img2.wikia.nocookie.net/__cb20141120133208/epicrapbattlesofhistory/images/4/4b/A_Rock!.gif" id="rock">
    <img src="http://www.clipartpal.com/_thumbs/pd/education/paper_sheet.png" id="paper">
    <img src="http://www2.fiskars.com/var/fiskars_amer/storage/images/frontpage2/sewing-quilting/products/scissors-and-sharpeners/the-original-orange-handled-scissors-8/16933-6-eng-US/The-Original-Orange-Handled-Scissors-8_product_main.png" id="scissors">
</div>