Rock Paper Scissors

An example JS game for a friend.

by Spicybatts

HTML

<script src="https://rawgit.com/iAmMortos/JSConsole/master/console.min.js"></script>
<div id="contents">
    <button id="playButton">Play Rock Paper Scissors!</button>
    <p>Clicking this button calls the <code>rps()</code> function</p>
</div>

CSS

body
{
    
}

#contents
{
    width: 100%;
    text-align: center;
    margin-top: 50px;
    font-family: sans-serif;
}

#playButton
{
    font-size: 24px;
    padding: 20px;
    background-color: #64C800;
    border: solid 2px black;
    border-radius: 5px;
}
#playButton:hover
{
    background-color: #6EDC00;
    cursor: pointer;
}

JavaScript

// This function is the entire game. It's very short, but it simply outlines the steps of playing TicTacToe. It calls 3 other functions inside it.
function rockPaperScissors()
{
    console.log("\n\nWelcome to JOHN CENA *dah dadah daaaah*\n...I mean Rock Paper Scissors...\n");

    var userInput = getUserInput();
    var computerInput = getComputerInput();
    decideWinner(userInput, computerInput);
}

// Loops and gets valid user input, then returns it.
function getUserInput()
{
    // Any time you use a while loop, you HAVE to make sure you eventually leave the loop. You can do this by either using a "break;", a "return", or by eventually making the while loop's test return false.
    while (true)
    {
        // Get user input, no matter what it is.
        var userInput = prompt("Whatcha want? (rock/paper/scissors)");
		
        // This tests is a fancy shortcut for:
        // if (userInput === "rock" || userInput === "paper" || userInput === "scissors")
        // Which contains a lot of redundancy. It basically is saying
        // if the list "rock", "paper", "scissors" contains the userInput (exact match), then the user has chosen corrently. otherwise, they entered something that isn't acceptable.
        if (["rock", "paper", "scissors"].indexOf(userInput) === -1)
        {
            // Tell the user they goofed. The while(true) will ask them again.
            console.log("NOPE! Even though it's great, '" + userInput + "' is not one of the options, ya dingus! TRY AGAIN!");
        }
        else
        {
            // Good job, they did it.
            console.log("You have selected " + userInput + ".");

            //  This is what finally lets us out of the loop
            return userInput;
        }
    }
}

// Randomly generates the computer's choice, and returns it
function getComputerInput()
{
    var selection = "";
    // Another while loop? you ask.
    // Yes. I only do this for the extra precision, so that each value has the same...