Skip to content

Instantly share code, notes, and snippets.

@themarcba
Last active July 23, 2021 13:02
Show Gist options
  • Save themarcba/11972b92c63c3aa2160b6c998fb6ffa0 to your computer and use it in GitHub Desktop.
Save themarcba/11972b92c63c3aa2160b6c998fb6ffa0 to your computer and use it in GitHub Desktop.
// Standalone, dependency-free version of rock paper scissors
// Author: Marc Backes (@themarcba)
// Available choices and it's associated values
const choiceMap = { r: 'rock', p: 'paper', s: 'scissors' }
// Request an input from the user
const getInput = query => {
return new Promise((resolve, reject) => {
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout,
})
readline.question(`${query} `, choice => {
readline.close()
resolve(choice.toLowerCase())
})
})
}
// Make the computer pick a move
const aiMove = () => {
const possibilities = Object.values(choiceMap)
const randomIndex = Math.floor(Math.random() * possibilities.length)
return possibilities[randomIndex]
}
// Make the player pick a move
const playerMove = async () => {
return new Promise(async (resolve, reject) => {
let input = ''
// Avoid wrong inputs
while (!(input in choiceMap)) {
input = await getInput('Rock, Paper, Scissors? (R/P/S)')
if (!(input in choiceMap)) console.log(`Invalid choice. Try again.`)
else resolve(choiceMap[input])
}
})
}
// Tell whether the player won or lost
const evaluate = (ai, player) => {
if (ai === player) return 'draw'
if (player === 'rock' && ai === 'scissors') return 'win'
if (player === 'paper' && ai === 'rock') return 'win'
if (player === 'scissors' && ai === 'paper') return 'win'
return 'lose'
}
// Run the game in an endless loop
const run = async () => {
const score = { ai: 0, player: 0 }
while (true) {
console.log('-----------------------------------')
// Gather inputs and evaluate
const ai = aiMove()
const player = await playerMove()
const result = evaluate(ai, player)
// Output results
console.log(`You played ${player}`)
console.log(`The AI played ${ai}`)
console.log(result)
if (result === 'draw') {
console.log(`It's a draw!`)
} else if (result === 'win') {
console.log(`You won!`)
score.player++
} else if (result === 'lose') {
console.log(`You lost!`)
score.ai++
}
console.log('Current scores:', { score })
}
}
run()
@themarcba
Copy link
Author

To run this, just feed it to Node.js. No further steps are required.

node rock-paper-scissors.js

@themarcba
Copy link
Author

Half of this code you see here was written by GitHub Copilot 🤖

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment