spilledmilk
7/25/2016 - 11:06 PM

rolling-a-character.js

var prompt = require('prompt');
var util = require('util');

var Player = function(options) {
  this.name = options.name;
  this.attributes = options.attributes || {
    str: 10,
    int: 10,
    wis: 10,
    dex: 10,
    cha: 10
  };

  return this;
};

var singleRoll = function(from, to) {
  return Math.floor(Math.random() * (to-from)) + from;
};

var checkRoll = function(p, attrs, cb) {
  prompt.start();
  prompt.get(['result'], function(err, result) {
    accept = (result['result'].toLowerCase() === 'y');
    if (!accept) {
      roll(p, cb);
    } else {
      p.attributes = attrs;
      cb(p);
    };
  });
};

var rollAttrs = function() {
  return {
    str: singleRoll(12, 20),
    int: singleRoll(12, 20),
    wis: singleRoll(12, 20),
    dex: singleRoll(12, 20),
    cha: singleRoll(12, 20)
  }
};

var printRoll = function(attributes) {
  console.log(util.format("You rolled str: %d ine: %d wis: %d dex: %d char: %d", 
                       attributes.str, attributes.int,
                       attributes.wis, attributes.dex,
                       attributes.cha));
};

var roll = function(p, cb) {
  var attrs = rollAttrs();
  printRoll(attrs);
  checkRoll(p, attrs, cb);
};

var done = function(p) {
  console.log(p);
};

var player = new Player({name: 'bob'});
roll(player, done);