Skip to content

Instantly share code, notes, and snippets.

@stephenmathieson
Created February 8, 2013 14:53
Show Gist options
  • Save stephenmathieson/4739462 to your computer and use it in GitHub Desktop.
Save stephenmathieson/4739462 to your computer and use it in GitHub Desktop.
harris' rock paper scissors
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Rock, Paper, Scissors</title>
<script>
var options = [ 'rock', 'paper', 'scissors' ],
userChoice = null,
computerChoice = null,
result = null,
wins = {
'user': 0,
'computer': 0
};
function getResult() {
if (userChoice === computerChoice) {
return 'tie';
}
if (userChoice === 'paper' && computerChoice === 'rock') {
return 'user';
}
if (userChoice === 'scissors' && computerChoice === 'paper') {
return 'user';
}
if (userChoice === 'rock' && computerChoice === 'scissors') {
return 'user';
}
return 'computer';
}
function getUserChoice(message) {
message = message || 'rock, paper, or scissors?';
return prompt(message);
}
function play() {
var results = document.getElementById('results'),
score = document.getElementById('score'),
scoreHTML = '',
attempts = 0;
userChoice = getUserChoice();
while(options.indexOf(userChoice) === -1 && attempts < 5) {
userChoice = getUserChoice('please pick a valid option: rock, paper or scissors?');
attempts += 1;
}
computerChoice = options[Math.floor(Math.random() * options.length)];
result = getResult();
if (result === 'tie') {
results.innerHTML += '<p>you tied!</p>';
} else {
wins[result] += 1;
results.innerHTML += '<p>' + result + ' won!</p>';
}
scoreHTML += '<p>';
scoreHTML += 'user wins: ' + wins.user;
scoreHTML += '</p>';
scoreHTML += '<p>';
scoreHTML += 'computer wins: ' + wins.computer;
scoreHTML += '</p>';
score.innerHTML = scoreHTML;
}
</script>
</head>
<body>
<div id="results"></div>
<div id="score"></div>
<button onclick="play()">play</button>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment