I am trying to implement a CLI version of the Rock Paper Scissors game. I am using the inquirer module to handle IO. My main function looks like this:
RockPaperScissors.prototype.gameLoop = function()
{
var x;
var Promise = require('bluebird');
//simple promise test
//this.playGame().then(function(){ console.log("The end");});
Promise.coroutine(function*()
{
//for(x=0;x<this.maxTurns;x++)
//{
console.log('Printing '+ x.toString());
var action = yield this.playGame();
//}
if(this.playerScore > this.serverScore) { console.log('Player wins match');} else {console.log('Server wins match'); }
});
};
exports.RockPaperScissors = RockPaperScissors;
The playGame() function returns a promise made by using new Promise(). If I do this:
this.playGame().then(function(){ console.log("The end");});
The promise executes correctly. However, when used inside Promise.coroutine(), nothing is executed. What am I missing here?
This is the code for the playGame() function:
RockPaperScissors.prototype.playGame = function()
{
var inq = require('inquirer');
var rand = require('random-js');
var _ = require('lodash');
var promise = require('bluebird');
//make possibilities local
var possibilities = this.possibilities;
console.log ('------------------ Stats ----------------');
console.log ('Player: ' +this.playerScore+' Server: '+this.serverScore);
console.log ('-----------------------------------------');
var question1 ={
type:'rawlist',
name:'option',
message:'Please choose Rock, paper or scissors:',
choices:['Rock','Paper','Scissors']
};
return new promise(function(resolve,reject)
{
inq.prompt([question1],function(answers)
{
console.log('You chose '+answers.option);
var playerObject = answers.option;
//random with Mersenne Twister API
var r = new rand(rand.engines.mt19937().autoSeed());
var myPlay =r.integer(0,2);
var serverObject ='';
switch(myPlay)
{
case 0:
serverObject='Rock';
break;
case 1:
serverObject ='Paper';
break;
case 2:
serverObject='Scissors';
break;
}
var result='', action='';
//choose winner by using a lodash function!
_.forEach(possibilities,function(e){
if (e[0]==serverObject && e[1] ==playerObject)
{
result=e[2];
action=e[3];
}
});
console.log('I chose ' + serverObject+ "\n")
console.log (result);
if (action=='win') {this.playerScore++;}
if (action=='lose'){this.serverScore++;}
resolve(action);
});
});
};