1

I'm learning plain JavaScript on the command line, using Node.js to execute my scripts.

I've been trying to rewrite a simple Ruby implementation of 'Towers of Hanoi'.

Here is some of my code so far:

function Tower() {
  this.rods = [[8, 7, 6, 5, 4, 3, 2, 1], [], []];
  this.gameOver = false;
}

Tower.prototype.showTowers = function () {
  var i;
  for (i = 0; i < 3; i++) {
    console.log(i + 1 + ': ' + this.rods[i]);
  }
};

Tower.prototype.moveRod = function (from, to) {
  ...
}

I am struggling with writing the play loop. I think the issue is that I'm not familiar with asynchronous functions. My play loop pseudocode is something like:

until game.win? {
  game.show_towers
  until valid_move?(move) {
    move = request_move
  }
  make_move(move)
}
game.congrats

I've tried prompt and readline. I'm assuming neither are 'blocking' because in both cases my while loop infinitely cycles through user input requests repeatedly without stopping.

Any advice?

Thanks.

seanomlor
  • 973
  • 1
  • 10
  • 23
  • Can you show us some real loop-code that you've tried? The pseudocode is logically correct, you just need to use callbacks and recursion instead of a loop. [Async's until](https://github.com/caolan/async#until) might make the code cleaner. – Andreas Hultgren Jun 17 '13 at 07:38
  • maybe you should consider use some kind of a cli module. look here for a nice example: https://blog.nodejitsu.com/writing-cli-apps-with-flatiron – pl47ypus Jun 17 '13 at 10:22
  • possible duplicate of [node.js: readSync from stdin?](http://stackoverflow.com/questions/3430939/node-js-readsync-from-stdin) – Jamund Ferguson Sep 03 '15 at 15:45

0 Answers0