1

I'm making a simple rock, paper, scissors game. And sometimes when I refresh the page nothing happens. When that happens, no errors are shown. I tried running this code on an online editor like w3schools, but the result is the same. What could be causing this problem?

Here's my code:

<body onload="game()">
    <script>
        function game(playerItem, computerSelection) {
        
            function computerSelection() {
                var arr = ["rock", "paper", "scissors"];
                var computerSelection = arr[Math.floor(Math.random() * 3)];
                return computerSelection;
            }
        
            var playerItem = "rock";
        
            if (playerItem == "rock" & computerSelection() == "paper") {
                document.write(rockVSpaper);
                return;
            };
            if (playerItem == "rock" & computerSelection() == "scissors") {
                document.write(rockVSscissors);
                return;
            };
            if (playerItem == "rock" & computerSelection() == "rock") {
                document.write(rockVSrock);
                return;
            };
        }
        var rockVSpaper = "You lose! The computer's paper wraps your rock.";
        var rockVSscissors = "You won! Your rock make the computer's scissors blunt.";
        var rockVSrock = "Tie! A Rock doesn't do anything with another rock.";
    </script>
</body>
Omar Einea
  • 2,478
  • 7
  • 23
  • 35
MaRK
  • 49
  • 1
  • 8
  • 1
    Not the total solution to your issue but: you are using the `&` bitwise operator, instead you should use the `&&` logical AND operator when you want both conditions to be true (https://stackoverflow.com/questions/7310109/whats-the-difference-between-and-in-javascript) – yuriy636 Jan 07 '18 at 11:03

1 Answers1

3

It's sometimes not working because you're running computerSelection() three times inside your if statements' conditions. This means every time you check, you generate a new random computer selection which means all three if conditions could equal to false.

To solve this, you should run computerSelection() once and store what it generates in a variable, then use that in your if statements. Like so:

var playerItem = "rock";
var computerItem = computerSelection();

if (playerItem == "rock" && computerItem == "paper") {
    document.write(rockVSpaper);
    return;
};
// The rest of the if statements and code...

Here's a codepen after applying the mentioned modifications.

Omar Einea
  • 2,478
  • 7
  • 23
  • 35