Skip to content

Instantly share code, notes, and snippets.

@derekconjar
Last active July 16, 2016 00:37
Show Gist options
  • Save derekconjar/cd9b8119680f0cdbdea0c2fc3a16739d to your computer and use it in GitHub Desktop.
Save derekconjar/cd9b8119680f0cdbdea0c2fc3a16739d to your computer and use it in GitHub Desktop.
RockPaperScissors - an overengineered and charmingly rude JavaScript rock paper scissors game that I wrote when I was bored.
;(function () {
var RockPaperScissors = function (opts) {
this.opts = opts ? opts : {};
this.scoreboard = [];
this.choices = [];
this.truthtable = this.opts.truthtable || {
rock: ['scissors'],
paper: ['rock'],
scissors: ['paper']
};
this.messages = {
prompt: 'Rock, paper, scissors? Pick one:',
afterWin: 'You win. Nicely done, you filthy bastard.',
afterLoss: 'You lose. Serves you right, asshole!',
afterTie: "It's a tie! Holy fuck.",
playAgain: 'Would you like to play again? Y or N',
invalidAnswer: "That wasn't one of the options, dummy."
};
this.init = function () {
this.populateChoices();
this.playRound();
};
this.playRound = function () {
var choice = this.promptPlayer();
if (this.isValidAnswer(choice)) {
this.announceWinner(choice, this.pickRandomChoice());
} else {
alert(this.messages.invalidAnswer);
}
if (prompt(this.messages.playAgain) === 'Y') {
return this.playRound();
}
alert('Goodbye!');
};
this.pickRandomChoice = function () {
var i = Math.floor(Math.random() * this.choices.length);
return this.choices[i];
};
this.promptPlayer = function () {
return prompt(this.messages.prompt).toLowerCase();
};
this.isValidAnswer = function (answer) {
return this.choices.indexOf(answer) !== -1;
};
this.populateChoices = function () {
this.choices = Object.keys(this.truthtable);
};
this.xBeatsY = function (x, y) {
return this.truthtable[x].indexOf(y) !== -1;
};
this.announceWinner = function (playerChoice, computerChoice) {
var message = 'The computer picked ' + computerChoice + '...\n\n';
if (playerChoice === computerChoice) {
return alert(message + this.messages.afterTie);
}
if (this.xBeatsY(playerChoice, computerChoice)) {
return alert(message + this.messages.afterWin);
}
return alert(message += this.messages.afterLoss);
};
this.init();
};
window.RockPaperScissors = RockPaperScissors;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment