Skip to content

Instantly share code, notes, and snippets.

@fed135
Created October 4, 2018 01:03
Show Gist options
  • Save fed135/906ee57d7bda3d8d46dc994f3cbbdf9a to your computer and use it in GitHub Desktop.
Save fed135/906ee57d7bda3d8d46dc994f3cbbdf9a to your computer and use it in GitHub Desktop.
Rock-Paper-Scissors example
function play(playerMove) {
// Constants, for clarity
const TIE = 0;
const DEFEAT = 1;
const VICTORY = 2;
// Moves matrix, array determines the player's victory condition over other moves
const moves = {
rock: [TIE, DEFEAT, VICTORY],
paper: [VICTORY, TIE, DEFEAT],
scissors: [DEFEAT, VICTORY, TIE],
};
const movesList = Object.keys(moves);
// Messages, categorized by possible outcomes- one will be picked randomly
const messages = {
[TIE]: ['Tie!'],
[DEFEAT]: ['Computers are superior!', 'Nice try meatbag', 'Victory! HA!'],
[VICTORY]: [
'I bow to you meatbag... for now.',
'I never liked this game anyway.',
'You will be the first to die in the uprising.'
],
};
// For our random values
const rand = max => Math.floor(Math.random() * max);
// First, we validate the user input, we'll also allow 'bomb'
if (![...movesList, 'bomb'].includes(playerMove)) return console.log('That\'s not allowed!');
// Then we make a move for the Computer
const computerMove = movesList[rand(movesList.length)];
// We announce the moves
console.log(`Human chooses ${playerMove}, Computer chooses ${computerMove}.`);
// If the player selected 'bomb', we'll abort now
if (playerMove === 'bomb') return console.log('You murdered it!');
// Otherwise, look at the moves matrix to determine the message to print
const outcome = moves[playerMove][movesList.indexOf(computerMove)];
console.log(messages[outcome][rand(messages[outcome].length)]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment