Rock, Paper, Scissors
by Weston Ruter
HTML
<p>
<button onclick="rock()" type=button>π» Rock</button>
<button onclick="paper()" type=button>π Paper</button>
<button onclick="scissors()" type=button>βοΈ Scissors</button>
</p>
<p id="result">
Click a button!
</p>
CSS
body {
text-align: center;
}
button {
font-size: 20px;
}
#result {
font-size: 20px;
}
JavaScript
const ROCK = 0;
const PAPER = 1;
const SCISSORS = 2;
function rock() {
play( ROCK );
}
function paper() {
play( PAPER );
}
function scissors() {
play( SCISSORS );
}
function showResult( resultMessage ) {
document.getElementById( 'result' ).textContent = resultMessage;
}
function play( myChoice ) {
const computerChoice = getComputerChoice();
if ( myChoice === computerChoice ) {
showResult( 'It is a tie!!! Try again.' );
} else if ( myChoice === ROCK && computerChoice === SCISSORS ) {
showResult( 'I win!!! π ' );
} else if ( myChoice === ROCK && computerChoice === PAPER ) {
showResult( 'I lose!!! π ' );
} else if ( myChoice === PAPER && computerChoice === SCISSORS ) {
showResult( 'I lose!!! π ' );
} else if ( myChoice === PAPER && computerChoice === ROCK ) {
showResult( 'I win!!! π ' );
} else if ( myChoice === SCISSORS && computerChoice === ROCK ) {
showResult( 'I lose!!! π ' );
} else if ( myChoice === SCISSORS && computerChoice === PAPER ) {
showResult( 'I win!!! π ' );
}
}
/**
* Get computer answer.
*
* This function returns a random number of either 0, 1, or 2.
* The number 0 means ROCK!
* The number 1 means PAPER!
* The number 2 means SCISSORS!
*/
function getComputerChoice() {
return Math.floor( Math.random() * 3 );
}