Created
May 8, 2014 15:42
-
-
Save chochinlu/65df898ade7067cbe149 to your computer and use it in GitHub Desktop.
Simple rock, paper, scissors game.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// include required lib | |
var readline = require('readline'); | |
/// Generate computer answer | |
var ComputerAns = function(){ | |
var num = Math.random(); | |
//console.log(num); | |
if (num < 0.34) return 'rock'; | |
if (num >= 0.34 && num < 0.67) return 'paper'; | |
if (num >= 0.67) return 'scissors'; | |
}; | |
/// Show Compared result | |
var Result = function(yourAns, compAns){ | |
if (yourAns === compAns) return 'tie!'; | |
if (yourAns === 'rock' && compAns === 'scissors') return 'You Win!'; | |
if (yourAns === 'scissors' && compAns === 'rock') return 'Computer Win!'; | |
if (yourAns === 'paper' && compAns === 'rock') return 'You Win!'; | |
if (yourAns === 'rock' && compAns === 'paper') return 'Computer Win!'; | |
if (yourAns === 'scissors' && compAns === 'paper') return 'You Win!'; | |
if (yourAns === 'paper' && compAns === 'scissors') return 'Computer Win!'; | |
}; | |
/// Print your answer, computer answer, and compared result | |
var CompareWithComputer = function(yourAns){ | |
var compAns = ComputerAns(); | |
console.log('-------------------------------------------'); | |
console.log('your choice is ', yourAns); | |
console.log('computer choice is ',compAns); | |
console.log(Result(yourAns, compAns)); | |
console.log('------------------------------------------- \n'); | |
}; | |
/// Create a Command Line Interface to let user key in value and show value in console. | |
var rl = readline.createInterface({ | |
input: process.stdin, | |
output: process.stdout | |
}); | |
// Set and show prompt | |
rl.setPrompt('Do you choose rock, paper or scissors? '); | |
rl.prompt(); | |
// check the line input | |
rl.on('line', function(line){ | |
switch(line.trim()){ | |
case 'rock': | |
CompareWithComputer('rock'); | |
break; | |
case 'paper': | |
console.log('good choice!'); | |
break; | |
case 'scissors': | |
console.log('good choice!'); | |
break; | |
default: | |
console.log('You answer is `'+ line.trim() + | |
'`, please choose rock, paper, or scissors \n'); | |
break; | |
} | |
rl.prompt(); | |
}).on('close', function(){ | |
console.log('\n\n ByeBye ! Have a nice day!\n\n'); | |
process.exit(); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment